Demo:
package com.dom4j.red;import java.io.File;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;/** * 把xml文档信息封装到对象中 * @author zhiyong * */public class Demo4 { public static void main(String[] args) throws DocumentException { //建立xml解析器对象 SAXReader reader = new SAXReader(); //读取xml文件,返回Document对象 Document document = reader.read(new File("./src/contact2.xml")); //读取根标签 Element root = document.getRootElement(); //定义集合,放入标签里面的所有属性和值 List<Contact> contactList = new ArrayList(); //获取传入标签下的所有直接子标签 List<Element> list = root.elements(); for(Element ele : list){ Contact con = new Contact(); //获取标签的属性和值 con.setId(ele.attributeValue("id")); con.setAge(ele.elementText("age")); con.setName(ele.elementText("name")); con.setPhone(ele.elementText("phone")); con.setEmail(ele.elementText("email")); con.setQq(ele.elementText("qq")); contactList.add(con); } for(Contact c : contactList){ // System.out.println("Contact[id=\"" + c.getId() + "\" name=\"" + c.getName() + "\" phone=\"" + c.getPhone() + "\" email=\"" + c.getEmail() + "\" qq=\"" + c.getQq() + "\"]" ); System.out.println(c); } }}
Contact类
package com.dom4j.red;public class Contact { private String id; private String name; private String age; private String phone; private String email; private String qq; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } @Override public String toString() { return "Contact [id=" + id + ", name=" + name + ", age=" + age + ", phone=" + phone + ", email=" + email + ", qq=" + qq + "]"; }}
xml文档
<?xml version="1.0" encoding="utf-8"?><contactList> <contact id="001"> <name>木丁西</name> <age>18</age> <phone>18071897425</phone> <email>1012421396@qq.com</email> <qq>1012421396</qq> </contact> <contact id="002"> <name>刘先森</name> <age>20</age> <phone>18771897466</phone> <email>561242139@qq.com</email> <qq>561242139</qq> </contact></contactList>
效果: