DOM4J 方式解析 XML 数据
1.DOM4J 解析 XML 的步骤
XML:
<?xml version="1.0" encoding="UTF-8"?>
<persons xsi:noNamespaceSchemaLocation="{some.xsd}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<person id="1001">
<name>张三</name>
<age>18</age>
</person>
<person id="1002">
<name>李四</name>
<age>20</age>
</person>
</persons>
解析代码:
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Text{
public static void main(String[] args) throws DocumentException {
//创建SAXReader对象
SAXReader reader=new SAXReader();
//调用read方法
Document doc=reader.read(new File("some.xml"));
//获取根元素
Element root=doc.getRootElement();//Persons
//通过迭代器遍历直接节点
for(Iterator<Element> itePerson = root.elementIterator(); itePerson.hasNext();){
Element personEle=itePerson.next();
//得到person的属性
for(Iterator<Attribute> iteAtt = personEle.attributeIterator(); iteAtt.hasNext();){
Attribute att=iteAtt.next();
System.out.println(att.getName()+"\t"+att.getText());
}
}
System.out.println("\n----------------------");
List<Person> personList=new ArrayList<Person>();
for(Iterator<Element> itePerson=root.elementIterator();itePerson.hasNext();){
//创建Person对象
Person person=new Person();
Element personEle=itePerson.next();//得到每一个person
//使用for循环继续遍历
for(Iterator<Element> subPersonEle=personEle.elementIterator();subPersonEle.hasNext();){
//得到每一个子元素
Element subEle=subPersonEle.next();
System.out.println(subEle.getName()+"\t"+subEle.getText());
/**
* 封装成Person对象
* */
//获取节点的名称
String nodeName=subEle.getName();//name,age
//使用switch判断
switch (nodeName) {
case "name":
person.setName(subEle.getText());
break;
case "age":
person.setAge(Integer.parseInt(subEle.getText()));
break;
}
}
//添加到集合中
personList.add(person);
}
//遍历集合
System.out.println("\n遍历集合-----------------------\n");
for (Person p : personList) {
System.out.println((p.getName() + "\t" + p.getAge()));
}
}
}
效果图:
2.四种解析 XML 的特点
- DOM 解析:
形成了树结构,有助于更好的理解、掌握,且代码容易编写。
解析过程中,树结构保存在内存中,方便修改 - SAX 解析:
采用事件驱动模式,对内存耗费比较小。
适用于只处理 XML 文件中的数据时 - JDOM 解析:
仅使用具体类,而不使用接口。
API 大量使用了 Collections 类 - DOM4J 解析:
JDOM 的一种智能分支,它合并了许多超出基本 XML 文档表示的功能。
它使用接口和抽象基本类方法。
具有性能优异、灵活性好、功能强大和极端易用的特点。 是一个开放源码的文件