这是我第一次写博客,今天初次接触XML文件的解析,感觉有点绕,但是最后还是自己做出来了,想想还是写写吧,记录自己的成长历程
xml文件样式:
张三
23
USA李四
24
USA王五
25
USAJava代码:
package com.gem.java.parsexml;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class CompleteParseXML {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse("src/hello.xml");
Element students=document.getDocumentElement();
System.out.print("");
NodeList stuNodeList=students.getChildNodes();
for (int i = 0; i < stuNodeList.getLength(); i++) {
Node stuNode=stuNodeList.item(i);
printNode(stuNode);
}
System.out.print(""+students.getNodeName()+">");
}
static void printNode(Node node){
if(node.getNodeType()==Node.ELEMENT_NODE){
System.out.print("
NamedNodeMap attr=node.getAttributes();
for (int i = 0; i < attr.getLength(); i++) {
Node attrNode=attr.item(i);
System.out.print(" "+attrNode.getNodeName()+"=\""+attrNode.getNodeValue()+"\"");
}
System.out.print(">");
NodeList childsNode=node.getChildNodes();
for (int i = 0; i < childsNode.getLength(); i++) {
Node childNode=childsNode.item(i);
printNode(childNode);
}
System.out.print(""+node.getNodeName()+">");
}else {
System.out.print(node.getNodeValue());
}
}
}
首先要获取到文档的根节点元素,节点有元素节点,属性节点,文本节点。标签 下有七个子节点,这个很容易被弄错,红色标出的是4个文本节点,另外3个标签是元素节点。我个人感觉DOM操作的API有点不按套路出牌,比如获取节点NodeList类型变量中获取子节点用item(index),我直接用了get(index),发现不对,又用了数组的取值方式,也是不对,最后才弄出来,还有获取其长度时使用getLength(),而不是length或者size(),这些都是要注意的,很容易因为惯性就写错了。我代码写的不是很好,如果有什么问题和建议欢迎大家给我提,就写到这吧。加油!