person.xml
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="1">
<name>Jerry</name>
<age>23</age>
</person>
<person id="3">
<name>Lily</name>
<age>17</age>
</person>
</persons>
針對person建立javabean,(因為我們下面要以對象的形式擷取此xml檔案內容)
package cn.partner4java.xml.bean;
public class Person {
private int id;
private String name;
private short age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public short getAge() {
return age;
}
public void setAge(short age) {
this.age = age;
}
/**
* 使用Dom解析xml檔案
*
*/
public class DomXMLReader {
public static List<Person> readXML(InputStream inStream) {
List<Person> persons = new ArrayList<Person>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(inStream);
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("person");//尋找所有person節點
for (int i = 0; i < items.getLength(); i++) {
Person person = new Person();
//得到第一個person節點
Element personNode = (Element) items.item(i);
//擷取person節點的id屬性值
person.setId(new Integer(personNode.getAttribute("id")));
//擷取person節點下的所有子節點(標籤之間的空白節點和name/age元素)
NodeList childsNodes = personNode.getChildNodes();
for (int j = 0; j < childsNodes.getLength(); j++) {
Node node = (Node) childsNodes.item(j); //判斷是否為元素類型
if(node.getNodeType() == Node.ELEMENT_NODE){ Element childNode = (Element) node;
//判斷是否name元素
if ("name".equals(childNode.getNodeName())) {
//擷取name元素下Text節點,然後從Text節點擷取資料 person.setName(childNode.getFirstChild().getNodeValue());
} else if (“age”.equals(childNode.getNodeName())) {
person.setAge(new Short(childNode.getFirstChild().getNodeValue()));
}
}
}
persons.add(person);
}
inStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return persons;
}