DOM XML 解析方式是最容易理解的,它將XML文件作为Document对象读取到内存中,然后你可以轻松地遍历不同的元素和节点对象。遍历元素和节点不需要按照顺序进行。
DOM解析方式适合尺寸较小的XML文件,由于它將整个XML文件全部装载到内存中处理,所以不太适合处理尺寸较大的XML文件。对于较大的XML文件需要使用SAX解析。
在本教程中我们将对XML文件读取和解析,并用它来创建对象。下面是我们将要解析的XML文件。
employee.xml
<?xml version="1.0"?>
<Employees>
<Employee>
<name>Pankaj</name>
<age>29</age>
<role>Java Developer</role>
<gender>Male</gender>
</Employee>
<Employee>
<name>Lisa</name>
<age>35</age>
<role>CSS Developer</role>
<gender>Female</gender>
</Employee>
</Employees>
这个XML文件的内容是一些员工信息列表,因此我们需要创建一个Employee类来表示员工,然后將XML文件信息读取到程序中。
下面是Employee类的定义:
package com.journaldev.xml;
public class Employee {
private String name;
private String gender;
private int age;
private String role;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "Employee:: Name=" + this.name + " Age=" + this.age + " Gender=" + this.gender +
" Role=" + this.role;
}
}
需要注意的是这里我重写了toString()方法以便打印出员工对象的有用信息。接下来我们在程序中使用DOM解析方式读取XML文件来获取Employee 对象列表。
XMLReaderDOM.java
package com.journaldev.xml;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XMLReaderDOM {
public static void main(String[] args) {
String filePath = "employee.xml";
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nodeList = doc.getElementsByTagName("Employee");
//now XML is loaded as Document in memory, lets convert it to Object List
List<Employee> empList = new ArrayList<Employee>();
for (int i = 0; i < nodeList.getLength(); i++) {
empList.add(getEmployee(nodeList.item(i)));
}
//lets print Employee list information
for (Employee emp : empList) {
System.out.println(emp.toString());
}
} catch (SAXException | ParserConfigurationException | IOException e1) {
e1.printStackTrace();
}
}
private static Employee getEmployee(Node node) {
//XMLReaderDOM domReader = new XMLReaderDOM();
Employee emp = new Employee();
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
emp.setName(getTagValue("name", element));
emp.setAge(Integer.parseInt(getTagValue("age", element)));
emp.setGender(getTagValue("gender", element));
emp.setRole(getTagValue("role", element));
}
return emp;
}
private static String getTagValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodeList.item(0);
return node.getNodeValue();
}
}
程序输出内容如下:
Root element :Employees
Employee:: Name=Pankaj Age=29 Gender=Male Role=Java Developer
Employee:: Name=Lisa Age=35 Gender=Female Role=CSS Developer
在实际情况下,我们在解析XML文件之前先要对XML文件的合法性进行校验,学习如何使用XSD校验XML文件。
原文地址:http://www.journaldev.com/898/how-to-read-an-xml-file-in-java-dom-parser