一 、DOM方式
1 、xml文件
<?xml version="1.0" encoding="UTF-8"?>
<players>
<player id="1">
<name>kobe</name>
<height>2.01m</height>
<nickname>黑曼巴</nickname>
</player>
<player id="2">
<name>wade</name>
<height>1.93m</height>
<nickname>闪电侠</nickname>
</player>
</players>
2 、解析代码
package com.souche.sts.demo;
import java.io.File;
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;
/**
* 功能:dom xml解析
* @author sxl
*
*/
class Client {
public static void main(String args[]) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.parse(new File("E:\\player.xml"));
NodeList nodeList = d.getElementsByTagName("player");
System.out.println("共" + nodeList.getLength() + "个球员");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
NamedNodeMap attributes = node.getAttributes();
for (int j = 0; j < attributes.getLength(); j++) {
Node item = attributes.item(j);
System.out.println("属性名:" + item.getNodeName() + "===属性值:" + item.getNodeValue());
}
NodeList childNodes = node.getChildNodes();
for (int k = 0; k < childNodes.getLength(); k++) {
if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) {
Node childNode = childNodes.item(k);
System.out.println(childNode.getNodeName() + ":" + childNode.getFirstChild().getNodeValue());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
3 、结果
共2个球员
属性名:id===属性值:1
name:kobe
height:2.01m
nickname:黑曼巴
属性名:id===属性值:2
name:wade
height:1.93m
nickname:闪电侠
二 、DOM4J方式
public static void dom4j () {
SAXReader reader = new SAXReader();
try {
org.dom4j.Document read = reader.read(new File("E:\\player.xml"));
Element rootElement = read.getRootElement();
Iterator elementIterator = rootElement.elementIterator();
while (elementIterator.hasNext()) {
Element next = (Element)elementIterator.next();
List<Attribute> attributes = next.attributes();
for (Attribute e : attributes) {
System.out.println(e.getName() + ":" + e.getStringValue());
}
Iterator elementIterator2 = next.elementIterator();
while (elementIterator2.hasNext()) {
Element next2 = (Element)elementIterator2.next();
System.out.println(next2.getName() + ":" + next2.getStringValue());
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}