利用DOM简单的递归解析XML文档:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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;
public class ReadXML {
public static void main(String[] args) throws
Exception {
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db =
dbf.newDocumentBuilder();
//
文档根节点(数的入口,亦是文档解析的入口点)
Document doc =
db.parse("src/IP.xml"); // 文件路径,下面有文件的示例
IP.xml
// 根元素节点
Element root =
doc.getDocumentElement();
parseXML(root);
}
public static void parseXML(Element element)
{
System.out.print("
+ element.getNodeName());
// 获取元素的属性
NamedNodeMap nnm =
element.getAttributes();
// 进行属性判别
if (nnm != null) {
for (int i =
0; i < nnm.getLength(); i++) {
String
attrName = nnm.item(i).getNodeName();
String
attrValue = nnm.item(i).getNodeValue();
System.out.print("
" + attrName + "=\"" + attrValue + "\"");
}
}
System.out.print(">");
// 获取该元素的所有子节点s
NodeList list =
element.getChildNodes();
for (int j = 0; j
< list.getLength(); j++) {
Node node =
list.item(j);
short
nodeType = node.getNodeType();
// 元素
if (nodeType
== Node.ELEMENT_NODE) {
parseXML((Element)
node);
//
文本
} else if
(nodeType == Node.TEXT_NODE) {
System.out.print(node.getNodeValue());
//
注释
} else if
(nodeType == Node.COMMENT_NODE) {
System.out.print("");
}
}
System.out.print(""
+ element.getNodeName() + ">");
}
}
========================================== IP.xml
=====================================
encoding="UTF-8"?>
>
192.96.128.100
192.96.128.101
192.96.128.102
192.96.128.103