使用递归和dom遍历dom树形结构

Java代码  

package com.udp.test;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class ReadXML {


public static void main(String[] args) {


DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse("src/xml/employee.xml");
doc(doc);


} catch (Exception e) {
}
}


private static void doc(Document doc) {
NodeList list = doc.getChildNodes();
node(list);
}


private static void node(NodeList list) {
int len1 = list.getLength();
if (len1 == 0) {
return;
}
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if (node.getNodeType() == Node.TEXT_NODE) { // 文本节点
if (node.getTextContent().trim().length() > 0) {
System.out
.println("#TEXT: " + node.getTextContent().trim());
}
} else if (node.getNodeType() == Node.COMMENT_NODE) { // 注释节点
System.out.println("");
} else if (node.getNodeType() == Node.ELEMENT_NODE) {
if (node.hasChildNodes()) {
// 考虑只有文本节点的情况x的情况
int noneTextNodeCount = 0;
NodeList childs = node.getChildNodes();
for (int j = 0; j < childs.getLength(); j++) {
if (childs.item(j).getNodeType() != Node.TEXT_NODE
&& node.getNodeType() != Node.COMMENT_NODE) {
noneTextNodeCount++;
}
}
if (noneTextNodeCount != 0) {
System.out.print("<" + node.getNodeName() + " ");
NamedNodeMap atts = node.getAttributes();
if (atts != null) {
for (int j = 0; j < atts.getLength(); j++) {
Node att = atts.item(j);
if (att == null) {
continue;
}
System.out.print(att.getNodeName() + "='"
+ att.getNodeValue() + "' ");
}
}
System.out.print(">");
node(childs);
System.out.print("");
System.out.println();
} else {
// 只有文本节点x
System.out.print("<" + node.getNodeName() + " ");
NamedNodeMap atts = node.getAttributes();
if (atts != null) {
for (int j = 0; j < atts.getLength(); j++) {
Node att = atts.item(j);
if (att == null) {
continue;
}
System.out.print(att.getNodeName() + "='"
+ att.getNodeValue() + "' ");
}
}
System.out.print(">");
System.out
.print(childs.item(0).getTextContent().trim());
System.out.print("");
System.out.println();
}
} else {
// 没有子节点 这样的情况
System.out.print("<" + node.getNodeName() + " ");
NamedNodeMap atts = node.getAttributes();
if (atts != null) {
for (int j = 0; j < atts.getLength(); j++) {
Node att = atts.item(j);
if (att == null) {
continue;
}
System.out.print(att.getNodeName() + "='"
+ att.getNodeValue() + "' ");
}
}
System.out.print("/>");
System.out.println();
}
} else if (node.getNodeType() == Node.DOCUMENT_TYPE_NODE) {
System.out.println("");
}


}
}


}

你可能感兴趣的:(XML)