DOM4J解析XML文件
DOM4J
基于树形结构,第三方组件,效率更高,使用的Java中的迭代器实现数据读取,在web框架中使用较多(Hibernate)。
代码示例
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class DOM4JXmlDemo {
@Test
public void dom4jXmlParse() throws DocumentException {
//1. 创建DOM4J解析器对象
SAXReader reader = new SAXReader();
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("xml/person.xml");
Document doc = reader.read(is);
Element rootElement = doc.getRootElement();
Iterator<Element> iter1 = rootElement.elementIterator();
List<Person> persons = new ArrayList<>();
Person person = null;
while (iter1.hasNext()) {
person = new Person();
Element element = iter1.next();
person.setPersonId(element.attributeValue("personId"));
Iterator<Element> iter2 = element.elementIterator();
while (iter2.hasNext()) {
Element next = iter2.next();
String tag = next.getName();
if ("name".equals(tag)) {
person.setName(next.getText());
} else if ("address".equals(tag)) {
person.setAddress(next.getText());
} else if ("tel".equals(tag)) {
person.setTel(next.getText());
} else if ("fax".equals(tag)) {
person.setFax(next.getText());
} else if ("email".equals(tag)) {
person.setEmail(next.getText());
}
}
persons.add(person);
}
for (Person p : persons) {
System.out.println(p);
}
}
}
person.xml文件内容
<?xml version="1.0" encoding="UTF-8" ?>
<people>
<person personId="E01">
<name>Tony Blair</name>
<address>10 Download Street,London UK</address>
<tel>010-2586984</tel>
<fax>010-4567787</fax>
<email>blair@everywhere.com</email>
</person>
<person personId="E02">
<name>Json</name>
<address>10 Download Street,New York US</address>
<tel>010-2586484</tel>
<fax>010-4872127</fax>
<email>json@everywhere.com</email>
</person>
</people>