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

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

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


    jack
    21
    1990-02-01
    man
      2、 把下面的xml 转化为person集合


    0
    ok
    
        jack
        21
        1990-02-01
        man
    
    
        jack
        21
        1990-02-01
        man
    
    
        jack
        21
        1990-02-01
        man
    
   下面直接贴代码了:

   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 = "" + "jack" + "21"
				+ "1990-02-01" + "man"
				+ "";
		Person student = getPerson(xml);
		System.out.println(student.getName() + "|" + student.getAge() + "|"
				+ student.getBirthday() + "|" + student.getSex());
		System.out.println("person对象");
		String modelXMl = "jack" + "21"
				+ "1990-02-01" + "man";
		String xmlList = "" + "0" + "ok"
				+ "" + modelXMl + "" + ""
				+ modelXMl + "" + "" + modelXMl
				+ "" + "";
		System.out.println("person集合列表");
		List 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 getPersonList(String xml) {

		Document doc = null;
		List list = new ArrayList();
		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 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;
	}
}
运行结果:

使用dom4j 把xml格式解析为对象或者对象集合_第1张图片

你可能感兴趣的:(JAVA,android)