Demo4jdemo2:
package com.ag.Xml_demo;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class Demo4jdemo2 {
@Test
public void test01() throws DocumentException {
//准备一个ArrayList集合封装联系人信息
List<Contact> list = new ArrayList<>();
//创建SaxReader对象
SAXReader saxReader = new SAXReader();
//加载XML文件成为文档对象Document对象。
Document document = saxReader.read(Demo4jdemo2.class.getResourceAsStream("/Contacts.xml"));
//拿根元素
Element rootElement = document.getRootElement();
List<Element> contact = rootElement.elements("contact");
//遍历Contact子元素
for (Element element : contact) {
Contact contact1 = new Contact();
//封装对象
contact1.setId(Integer.valueOf(element.attributeValue("id")));
contact1.setVip(Boolean.valueOf(element.attributeValue("vip")));
contact1.setName(element.elementTextTrim("name"));
contact1.setEmail(element.elementTextTrim("email"));
contact1.setGender(element.elementTextTrim("gender").charAt(0));
//加入集合
list.add(contact1);
}
//遍历集合
for (Contact contact1 : list) {
System.out.println(contact1);
}
}
}
Contact:
package com.ag.Xml_demo;
public class Contact {
private String name;
private int id;
private boolean vip;
private char gender;
private String email;
public Contact() {
}
public Contact(String name, int id, boolean vip, char gendar, String email) {
this.name = name;
this.id = id;
this.vip = vip;
this.gender = gendar;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isVip() {
return vip;
}
public void setVip(boolean vip) {
this.vip = vip;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Contact{" +
"name='" + name + '\'' +
", id=" + id +
", vip=" + vip +
", gendar=" + gender +
", email='" + email + '\'' +
'}';
}
}
Contact.xml:
<?xml version="1.0" encoding="UTF-8"?>
<contactList>
<contact id="1" vip="true">
<name> 潘金莲 </name>
<gender>女</gender>
<email>panpan@itcast.cn</email>
</contact>
<contact id="2" vip="false">
<name>武松</name>
<gender>男</gender>
<email>wusong@itcast.cn</email>
</contact>
<contact id="3" vip="false">
<name>武大狼</name>
<gender>男</gender>
<email>wuda@itcast.cn</email>
</contact>
<user>
</user>
</contactList>
结果图:
![](https://i-blog.csdnimg.cn/blog_migrate/cc260ce4f161538d92f210f9b9b8808b.png)