XML文件时很多项目经常使用的配置或者其他用途的文件格式,解析xml文件格式的开发包也很多,本文主要使用java自带的DOM解析包。本文以一个实际例子来讲述解析xml文件的过程。
目标:解析这样一个XML文件
employees.xml
=======内容开始========
<?xml version="1.0" encoding="UTF-8"?>
<Personnel>
<Employee type="permanent">
<Name>Seagull</Name>
<Id>3674</Id>
<Age>34</Age>
</Employee>
<Employee type="contract">
<Name>Robin</Name>
<Id>3675</Id>
<Age>25</Age>
</Employee>
<Employee type="permanent">
<Name>Crow</Name>
<Id>3676</Id>
<Age>28</Age>
</Employee>
</Personnel>
=======内容结束========
目标是:输出如下内容
Employee Details - Name:Seagull, Type:permanent, Id:3674, Age:34.
Employee Details - Name:Robin, Type:contract, Id:3675, Age:25.
Employee Details - Name:Crow, Type:permanent, Id:3676, Age:28.
主要步骤
1,
- Get a document builder using document builder factory and parse the xml file to create a DOM object
- Get a list of employee elements from the DOM
- For each employee element get the id, name, age and type. Create an employee value object and add it to the list.
- At the end iterate through the list and print the employees to verify we parsed it right.
a) 获取document builder
b) 获取employee elements列表
Get the rootElement from the DOM object.From the root element get all employee elements. Iterate through each employee element to load the data.
c)读取每个员工的信息
d) I打印输出
截图: