DOM4J解析大致分为几步:
1.创建SAXReader 对象。
SAXReader sax = new SAXReader();
2.通过SAXReader对象使用read()方法读取文档。
Document doc=sax.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("MyXML/Student.xml"));
3.通过Document 文档对象获取根节点
Element root = doc.getRootElement();//获取根节点
4.根据根节点进行后面的操作
例子:
建立XML文档
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student score="23">
<name>"张三"</name>
<id>1003</id>
<sex>女</sex>
</student>
<student score="24">
<name>"李四"</name>
<id>1004</id>
<sex>男</sex>
</student>
<student id="1005">
<name>"张五"</name>
<score>25</score>
<sex>男</sex>
</student>
</students>
建立Students类
package MyXMl;
public class Students {
private int id;
private int socre;
private String name;
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getSocre() {
return socre;
}
public void setSocre(int socre) {
this.socre = socre;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Students [id=" + id + ", socre=" + socre + ", name=" + name + ", sex=" + sex + "]";
}
}
don4j解析:
package MyXMl;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
//dom4j解析,大量使用集合,需要导入第三方jar包
public class Dom4JParse {
public static void main(String[] args) throws Exception{
List<Students> list =new ArrayList<Students>();
SAXReader sax = new SAXReader();
// 使用read()读取文档
Document doc = sax.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("MyXML/Student.xml"));
Element root = doc.getRootElement();//获取根节点
List<Element> nodes = root.elements();//获取根节点下的子节点,返回List集合
//遍历每一个节点
for(Element e:nodes) {
//新建Student对象以便存储XML文件信息
Students stu = new Students();
//获取节点的属性,返回list集合
List<Attribute> arr = e.attributes();
for(Attribute a:arr) {
if("id".equals(a.getName())) {
stu.setId(Integer.parseInt(a.getValue()));//getValue()获取属性的值
}
if("sex".equals(a.getName())) {
stu.setSex(a.getValue());
}
if("score".equals(a.getName())) {
stu.setSocre(Integer.parseInt(a.getValue()));
}
if("name".equals(a.getName())) {
stu.setName(a.getValue());
}
}
//获取节点的子节点
List<Element> ele = e.elements();
for(Element e1:ele) {
if("id".equals(e1.getName())) {
stu.setId(Integer.parseInt(e1.getStringValue()));//getStringValue()获取节点的值
}
if("sex".equals(e1.getName())) {
stu.setSex(e1.getStringValue());
}
if("score".equals(e1.getName())) {
stu.setSocre(Integer.parseInt(e1.getStringValue()));
}
if("name".equals(e1.getName())) {
stu.setName(e1.getStringValue());
}
}
list.add(stu);
}
//输出信息测试
for(Students stu:list)
System.out.println(stu);
}
}
运行结果: