java 解析自定义xml_JAVA DOM4j解析XML数据到自定义javabean

我们获取xml中的数据,一般以面向对象的思想去处理这些数据。因此,我们需要自定义类来封装解析出来的数据,以方便我们操作这些数据。

自定义的java类,称为javabean。

自定义Contact类代码如下:这个类是用来封装解析出来的数据的。

package gz.itcast.a_dom4j_read;

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 [age=" + age + ", email=" + email + ", id=" + id

+ ", name=" + name + ", phone=" + phone + ", qq=" + qq + "]";

}

}

接下来把xml文档信息封装到对象中。

import java.io.File;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import org.dom4j.Document;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

/**

* 把xml文档信息封装到对象中

* @author APPle

*

*/

public class Demo4 {

public static void main(String[] args) throws Exception{

//使用集合封装对象

List list = new ArrayList();

//读取xml,封装对象

SAXReader reader = new SAXReader();

Document doc = reader.read(new File("./src/contact.xml"));

//读取contact标签

Iterator it = doc.getRootElement().elementIterator("contact");

while(it.hasNext()){

Element elem = it.next();

//创建Contact

Contact contact = new Contact();

contact.setId(elem.attributeValue("id"));

contact.setName(elem.elementText("name"));

contact.setAge(elem.elementText("age"));

contact.setPhone(elem.elementText("phone"));

contact.setEmail(elem.elementText("email"));

contact.setQq(elem.elementText("qq"));

list.add(contact);

}

for (Contact contact : list) {

System.out.println(contact);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值