XML的解析通常有DOM和SAX两种方式,JDK对这两种方式都提供了支持,相关API分布在 java.xml org.w3c.dom org.xml.sax包及其子包下面。
DOM方式对XML文件进行解析
XML DOM 和 JavaScript DOM非常相似,主要解析步骤
1 得到document对象
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
String path = DOMTest.class.getResource("/users.xml").getFile();
Document document = documentBuilder.parse(path);
2 获取要操作的元素
NodeList userNodeList = document.getElementsByTagName("user");
Element userElement = document.getElementById("u001");
3 进一步获得元素的内容(属性 文本内容 子元素)
String name = userElement.getAttribute("name");
String email = emailElement.getTextContent();
NodeList emailNodeList = userElement.getElementsByTagName("email");
实际例子:
XML文件内容
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student id="s1" name="tom">
<email>tom@tom.com</email>
<phone>12333333333</phone>
</student>
<student id="s2" name="lucy">
<email>tom@tom.com</email>
<phone>12333333333</phone>
</student>
</students>
解析代码:
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.NodeList;
public class dom_test {
public static void main(String[] args) throws Exception {
//得到document对象
DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
String path=dom_test.class.getResource("Students.xml").getFile();
Document document=documentBuilder.parse(path);
List<Student> list=new ArrayList<Student>();
//获得想要操作的元素
NodeList nodeList=document.getElementsByTagName("student");
for (int i = 0; i < nodeList.getLength(); i++) {
Element stuElement=(Element)nodeList.item(i);
Student stu=new Student();
//获取属性值
String id=stuElement.getAttribute("id");
String name=stuElement.getAttribute("name");
stu.setId(id);
stu.setName(name);
//获取子元素
NodeList emailNodeList=stuElement.getElementsByTagName("email");
for (int j = 0; j < emailNodeList.getLength(); j++) {
Element emailElement=(Element)emailNodeList.item(j);
String email=emailElement.getTextContent();
stu.setEmail(email);
}
NodeList phoneNodeList=stuElement.getElementsByTagName("phone");
for (int j = 0; j < phoneNodeList.getLength(); j++) {
Element phoneElement=(Element)phoneNodeList.item(j);
String phone=phoneElement.getTextContent();
stu.setPhone(phone);
}
System.out.println(stu);
}
System.out.println(list);
}
}