Java中解析XML文件的常用方式有三种,分别是:
- DOM解析
- SAX解析
- DOM4J解析
其中,DOM和SAX是Java内置提供的解析方式,无需引用JAR包;而DOM4J则是第三方提供的,需要引入相应JAR包才可使用。
DOM解析的基本步骤如下:
- 创建javax.xml.parsers.DocumentBuilderFactory对象(通过DocumentBuilderFactory的newInstance()方法)
- 创建javax.xml.parsers.DocumentBuilder对象(通过DocumentBuilderFactory的newDocumentBuilder()方法)
- 创建org.w3c.dom.Document对象(通过DocumentBuilder中的parse()方法)
xml解析器将xml文件加载到内存,然后构建出一个Document的树状图,通过Document对象获得树上的节点对象,通过对节点的访问获得xml文档的内容。所以在取得Document对象之后,我们只需要根据具体的业务需求,从Document对象中取出我们需要的数据即可。
xml解析的具体案例如下
xml文件定义如下
<?xml version="1.0" encoding="utf-8"?>
<contract>
<member id="001">
<name>张三</name>
<age>18</age>
<tel>33570</tel>
</member>
<member id="002">
<name>李四</name>
<age>18</age>
<tel>36580</tel>
</member>
</contract>
Java代码如下
public class TestDemoG {
public static void main(String[] args) throws Exception {
//1.先定义要操作的XML文档资源路径
File file = new File("C:" + File.separator + "Users" + File.separator + "Scoot" +
File.separator + "Desktop" + File.separator + "TelephoneBook.xml");
//如果XML文档资源以输入流的方式进行读取
//InputStream inputStream = new FileInputStream(file);
//2.取得文档解析工厂类
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//3.取得文档解析器
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
//4.取得文档对象
Document document = documentBuilder.parse(file);
//5.取得DOM树中的所有member节点对象(NodeList接口对象)
NodeList memberList = document.getElementsByTagName("member");
//6.循环遍历取出内容
for (int x = 0; x < memberList.getLength(); x++) {
//取得member节点
Element memberElement = (Element) memberList.item(x);
//取得member节点的id属性节点的内容
String idValue = memberElement.getAttribute("id");
System.out.println(idValue);
//取得name子节点
Element nameElement = (Element) memberElement.getElementsByTagName("name").item(0);
//取得name节点下的文本节点的值
String nameTextValue = nameElement.getFirstChild().getNodeValue();
System.out.println(nameTextValue);
//取得age子节点
Element ageElement = (Element) memberElement.getElementsByTagName("age").item(0);
//取得age节点下的文本节点的值
String ageTextValue = ageElement.getFirstChild().getNodeValue();
System.out.println(ageTextValue);
//取得tel子节点
Element telElement = (Element) memberElement.getElementsByTagName("tel").item(0);
//取得age节点下的文本节点的值
String telTextValue = telElement.getFirstChild().getNodeValue();
System.out.println(telTextValue);
System.out.println("------------------------------------------------------------------");
}
}
}
输出结果如下
001
张三
18
110
------------------------------------------------------------------
002
李四
18
120
------------------------------------------------------------------