import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Dom4JDemo {
public static void main(String[] args) throws DocumentException {
//1.获取SaxReader
SAXReader saxReader = new SAXReader();
//2
Document document = saxReader.read(Thread.currentThread().getContextClassLoader().
getResourceAsStream("person.xml"));
//3.
Element element = document.getRootElement();
//4.
Iterator iterator = element.elementIterator();
Person p;
while(iterator.hasNext()){
p = new Person();
Element element2 = (Element) iterator.next();
p.setId(element2.attributeValue("personid"));
p.setName(element2.elementText("name"));
p.setAddress(element2.elementText("address"));
p.setTel(element2.elementText("tel"));
p.setFax(element2.elementText("fax"));
p.setEmail(element2.elementText("email"));
System.out.println(p);
}
}
}
****************************************
Person类
public class Person { private String id; private String name; private String address; private String tel; private String fax; private String email; public Person() { super(); // TODO Auto-generated constructor stub } public Person(String id,String name,String address,String tel,String fax,String email) { super(); this.id = id; this.name = name; this.address = address; this.tel = tel; this.fax = fax; this.email = email; } public String getId() { return id; } public String getName() { return name; } public String getAddress() { return address; } public String getTel() { return tel; } public String getFax() { return fax; } public String getEmail() { return email; } public void setId(String id) { this.id = id; } public void setName(String name) { this.name = name; } public void setAddress(String address) { this.address = address; } public void setTel(String tel) { this.tel = tel; } public void setFax(String fax) { this.fax = fax; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "Person [id=" + id + ",name=" + name + ",address=" + address + ",tel=" + tel + ",fax=" + fax + ",email=" + email + "]"; } } 原文链接:https://www.f2er.com/xml/294844.html