关闭

使用dom4j 把xml格式解析为对象或者对象集合

标签: xmldom4j解析 对象 集合
5579人阅读 评论(1) 收藏 举报
分类:

  android开发里经常会遇到后台传来xml格式的数据,需要我们把它们解析后变成对象或者集合, dom4j是一个Java的XML API,类似于jdom,用来读写XML文件的。dom4j是一个非常非常优秀的Java XML API,具有性能优异、所以我们用dom4j解析xml,把其转化为对象,或者集合,使用之前导入dom4j.jar架包

        1、把下面的xml 转化为person的对象

<resp>
    <name>jack</name>
    <age>21</age>
    <birthday>1990-02-01</birthday>
    <sex>man</sex>
</resp>
      2、 把下面的xml 转化为person集合

<resp>
    <desc>0</desc>
    <depict>ok</depict>
    <content>
        <name>jack</name>
        <age>21</age>
        <birthday>1990-02-01</birthday>
        <sex>man</sex>
    </content>
    <content>
        <name>jack</name>
        <age>21</age>
        <birthday>1990-02-01</birthday>
        <sex>man</sex>
    </content>
    <content>
        <name>jack</name>
        <age>21</age>
        <birthday>1990-02-01</birthday>
        <sex>man</sex>
    </content>
</resp>
   下面直接贴代码了:

   Person类:

  

 public class Person {

	 private String name;
	 private String age;
	 private String birthday;
	 private String sex;
	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 getBirthday() {
		return birthday;
	}
	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	 

}


   Dom4jUtil类

 

import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;

public class Dom4jUtil {

	/**
	 * @param args
	 * @throws DocumentException
	 */
	public static void main(String[] args) throws DocumentException {
		// TODO Auto-generated method stub

		String xml = "<resp>" + "<name>jack</name>" + "<age>21</age>"
				+ "<birthday>1990-02-01</birthday>" + "<sex>man</sex>"
				+ "</resp>";
		Person student = getPerson(xml);
		System.out.println(student.getName() + "|" + student.getAge() + "|"
				+ student.getBirthday() + "|" + student.getSex());
		System.out.println("person对象");
		String modelXMl = "<name>jack</name>" + "<age>21</age>"
				+ "<birthday>1990-02-01</birthday>" + "<sex>man</sex>";
		String xmlList = "<resp>" + "<desc>0</desc>" + "<depict>ok</depict>"
				+ "<content>" + modelXMl + "</content>" + "<content>"
				+ modelXMl + "</content>" + "<content>" + modelXMl
				+ "</content>" + "</resp>";
		System.out.println("person集合列表");
		List<Person> list = getPersonList(xmlList);
		for (Person person : list) {
			System.out.println(person.getName() + "|" + person.getAge() + "|"
					+ person.getBirthday() + "|" + person.getSex());
		}
	}

	/**
	 * 把xml格式转化为person对象
	 * 
	 * @param xml
	 * @return
	 */
	public static Person getPerson(String xml) {
		Person person = null;
		InputSource in = new InputSource(new StringReader(xml));
		in.setEncoding("UTF-8");
		SAXReader reader = new SAXReader();
		Document document;
		try {
			document = reader.read(in);
			Element root = document.getRootElement();
			person = (Person) XmlUtil.fromXmlToBean(root, Person.class);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("数据解析错误");

		}
		return person;
	}

	/**
	 * 把xml转化为person集合
	 * 
	 * @param xml
	 * @return
	 */
	public static List<Person> getPersonList(String xml) {

		Document doc = null;
		List<Person> list = new ArrayList<Person>();
		try {

			// 读取并解析XML文档

			// SAXReader就是一个管道,用一个流的方式,把xml文件读出来

			// SAXReader reader = new SAXReader(); //User.hbm.xml表示你要解析的xml文档

			// Document document = reader.read(new File("User.hbm.xml"));

			// 下面的是通过解析xml字符串的

			doc = DocumentHelper.parseText(xml); // 将字符串转为XML

			Element rootElt = doc.getRootElement(); // 获取根节点

			System.out.println("根节点:" + rootElt.getName()); // 拿到根节点的名称

			String returnCode = rootElt.elementTextTrim("desc");
			if (!"0".equals(returnCode)) {
				System.out.println("后台数据返回有问题");
				return null;
			}

			Iterator<Element> it = rootElt.elementIterator("content");// 获取根节点下所有content
			while (it.hasNext()) {
				Element elementGroupService = (Element) it.next();
				Person baseBean = (Person) XmlUtil.fromXmlToBean(
						elementGroupService, Person.class);
				list.add(baseBean);
			}

		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("数据解析错误");
		}

		return list;
	}

}
     XmlUtil类:

import java.lang.reflect.Field;
import java.util.Date;

import org.dom4j.Element;

public class XmlUtil
{
	/**
	 * json 数据转换对象
	 * 
	 * @param Element
	 *            要转换的Element数据
	 * @param pojo
	 *            要转换的目标对象类型
	 * @return 转换的目标对象
	 * @throws Exception
	 *             转换失败
	 */
	@SuppressWarnings("rawtypes")
	public static Object fromXmlToBean(Element rootElt, Class pojo) throws Exception
	{
		// 首先得到pojo所定义的字段
		Field[] fields = pojo.getDeclaredFields();
		// 根据传入的Class动态生成pojo对象
		Object obj = pojo.newInstance();
		for (Field field : fields)
		{
			// 设置字段可访问(必须,否则报错)
			field.setAccessible(true);
			// 得到字段的属性名
			String name = field.getName();
			// 这一段的作用是如果字段在Element中不存在会抛出异常,如果出异常,则跳过。
			try
			{
				rootElt.elementTextTrim(name);
			}
			catch (Exception ex)
			{
				continue;
			}
			if (rootElt.elementTextTrim(name) != null && !"".equals(rootElt.elementTextTrim(name)))
			{
				// 根据字段的类型将值转化为相应的类型,并设置到生成的对象中。
				if (field.getType().equals(Long.class) || field.getType().equals(long.class))
				{
					field.set(obj, Long.parseLong(rootElt.elementTextTrim(name)));
				}
				else if (field.getType().equals(String.class))
				{
					field.set(obj, rootElt.elementTextTrim(name));
				}
				else if (field.getType().equals(Double.class) || field.getType().equals(double.class))
				{
					field.set(obj, Double.parseDouble(rootElt.elementTextTrim(name)));
				}
				else if (field.getType().equals(Integer.class) || field.getType().equals(int.class))
				{
					field.set(obj, Integer.parseInt(rootElt.elementTextTrim(name)));
				}
				else if (field.getType().equals(java.util.Date.class))
				{
					field.set(obj, Date.parse(rootElt.elementTextTrim(name)));
				}
				else
				{
					continue;
				}
			}
		}
		return obj;
	}
}
运行结果:


1
1

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:16675次
    • 积分:321
    • 等级:
    • 排名:千里之外
    • 原创:16篇
    • 转载:0篇
    • 译文:0篇
    • 评论:2条
    文章分类
    文章存档