XML解析之DOM4J

import java.util.Iterator;
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 + "]";
}

}



















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值