读取XML文件内容2(将内容封装到对象里面)

前端之家收集整理的这篇文章主要介绍了读取XML文件内容2(将内容封装到对象里面)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

实现的功能和上篇一样,只是将XML文件中的内容封装到一个对象中去

contact.xml

<?xml version="1.0" encoding="GBK"?>
<contactList>
    <contact id="001">
		<name>张三</name>
		<age>20</age>
		<phone>1234567</phone>
		<email>1234</email>
		<qq>222</qq>
	</contact>
	<contact id="002">
		<name>lisi</name>
		<age>20</age>
		<phone>1234567</phone>
		<email>1234</email>
		<qq>222</qq>
	</contact>
	<abc>
	    
	</abc>
</contactList>


Contact.java

//对象

package gz.itcast.a_dom4j_read;

public class Contact {
	public String id;
	public String name;
	public String age;
	public String phone;
	public String email;
	public 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
				+ "]";
	}
	
}


主程序:Dome3.java

package gz.itcast.a_dom4j_read;

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文档信息封装到对象中
 */
public class Demo3 {
	public static void main(String[] args) throws Exception {
		List<Contact> list = new ArrayList<Contact>();
		
		//读取XML文档,封装对象
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File("./src/contact.xml"));
		//读取contact标签
		Iterator<Element> 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);
		}
	}
}
原文链接:/xml/294579.html

猜你在找的XML相关文章