解析的文件Person.xml
<?xml version="1.0" encoding="utf-8"?>
<persons>
<person id="1" >
<name>小罗</name>
<age>21</age>
</person>
<person id="2">
<name>android</name>
<age>15</age>
</person>
</persons>
DOM解析工具类
package com.example.xmlparse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class DomParseUtils {
public static List<Person> parseXmlByDom(InputStream inputStream)
throws Exception {
List<Person> persons = new ArrayList<Person>();
// 得到一个DocumentBuilderFactory解析工厂类
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// 得到一个DocumentBuilder解析类
DocumentBuilder builder = factory.newDocumentBuilder();
// 接收一个xml的字符串来解析xml,Document代表整个xml文档
Document document = builder.parse(inputStream);
// 得到xml文档的根元素节点
Element personsElement = document.getDocumentElement();
// 得到标签为person的Node对象的集合NodeList
NodeList nodeList = personsElement.getElementsByTagName("person");
for (int i = 0; i < nodeList.getLength(); i++) {
Person person = new Person();
// 如果该Node是一个Element
if (nodeList.item(i).getNodeType() == Document.ELEMENT_NODE) {
Element personElement = (Element) nodeList.item(i);
// 得到id的属性值
String id = personElement.getAttribute("id");
person.setId(id);
// 得到person元素下的子元素
NodeList childNodeList = personElement.getChildNodes();
for (int j = 0; j < childNodeList.getLength(); j++) {
if (childNodeList.item(j).getNodeType() == Document.ELEMENT_NODE) {
// 解析到了person下面的name标签
if ("name".equals(childNodeList.item(j).getNodeName())) {
// 解析到了person下面的name标签
String nameString = childNodeList.item(j)
.getFirstChild().getNodeValue();
person.setName(nameString);
} else if ("age".equals(childNodeList.item(j)
.getNodeName())) {
String ageString = childNodeList.item(j)
.getFirstChild().getNodeValue();
person.setAge(Integer.parseInt(ageString));
}
}
}
persons.add(person);
person = null;
}
}
return persons;
}
}