通过dom方式解析整个xml文档步骤:
1.获得DocumentBuilderFactory对象, 获得文档解析器工厂. 解析文档要解析器 ------解析器工厂生产解析器
2.获得DocumentBuilder对象, 获得文档解析器 解析文档要文档解析器
3.获得Document对象 ,获得文档对象(文档根节点),即文档入口. 解析器做什么,就是把一个xml文件解析成Document对象。
4.获得文档根元素对象 ,多种方式获得文档根元素节点. 最常用就是Document对象.getDocumentElement().
5.获得根元素节点的名字。 getNodeName()方法。
6.获得根元素节点的属性. 属性都是键值对,很符合map形式。 所有为NamedNodeMap的对象。有个map
7.遍历拿到每一个属性的键和值。 通过getNodeName()和getNodeValue方法
8.获取根元素节点的子节点。判断子节点的类型。如果子节点为元素,递归调用上面的过程。
package com.spc.oa.xml.dom;
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 DomTest2 {
public static void main(String[] args) {
DocumentBuilder db = null;
Document document = null;
// 获得DOM解析器工厂
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// 获得DOM解析器
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
// 获得文档对象(根节点),即文档的入口
try {
document = db.parse("test.xml");
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 获得根元素节点
Element element = document.getDocumentElement();
parseElement(element);
}
private static void parseElement(Element element) {
//获得根元素节点的名字
String tagName = element.getNodeName();
System.out.print("<" + tagName);
//获得根元素的所有属性节点的map集合形式
NamedNodeMap map = element.getAttributes();
if (null != map && map.getLength() != 0) {
for (int i = 0; i < map.getLength(); i++) {
String name = map.item(i).getNodeName();
String value = map.item(i).getNodeValue();
System.out.print(" " + name + "='" + value +"'>");
}
} else if (map.getLength() == 0) {
System.out.print(">");
}
//拿到根元素节点的所有子节点
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
//遍历每一个子节点
Node node = children.item(i);
//获得每一个节点的类型
short nodeType = node.getNodeType();
if (nodeType == Node.ELEMENT_NODE || nodeType == Node.ATTRIBUTE_NODE) {
parseElement((Element)node);
}else if (nodeType == node.COMMENT_NODE) {
System.out.print("<!--"+ node.getTextContent() + "-->");
}else if (nodeType == Node.TEXT_NODE) {
System.out.print(node.getNodeValue());
}
}
System.out.print("</" + tagName + ">");
}
}