XStream轻松转换xml和java对象

首先引入所需的jar:

xstream-1.4.9、xpp3_min-1.1.4c、dom4j-1.6.1,

或用maven管理jar包时在pom.xml中添加:

<!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream -->
<dependency>
    <groupId>com.thoughtworks.xstream</groupId>
    <artifactId>xstream</artifactId>
    <version>1.4.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/xpp3/xpp3_min -->
<dependency>
    <groupId>xpp3</groupId>
    <artifactId>xpp3_min</artifactId>
    <version>1.1.4c</version>
</dependency>
<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>

实体类如下:

package com.cn.entity;

public class Address {

    //
    private String country;
    //
    private String province;
    //
    private String city;
    //
    private String county;
    //
    private String town;
    
    get...
    set...
}
package com.cn.entity;

import java.util.List;

public class Person {

    //姓名
    private String name;
    //性别
    private String sex;
    //年龄
    private int age;
    //地址
    private List<Address> Address;
    
    get...
    set...
}

XStream工具类:

package com.cn.util;

import com.cn.entity.Address;
import com.cn.entity.Person;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
/**
 * XStream工具类
 * @author sun.kai
 * 2016年8月13日
 */
public class XStreamUtil {

    private static XStream xStream;
    
    //JVM加载类时会执行这些静态的代码块,如果static代码块有多个,JVM将按照它们在类中出现的先后顺序依次执行它们,每个代码块只会被执行一次。
    static{
        xStream = new XStream(new DomDriver());
        /*
         * 使用xStream.alias(String name, Class Type)为任何一个自定义类创建到类到元素的别名
         * 如果不使用别名,则生成的标签名为类全名
         */
        xStream.alias("person", Person.class);
        xStream.alias("address", Address.class);
        //将某一个类的属性,作为xml头信息的属性,而不是子节点
        xStream.useAttributeFor(Address.class, "country");
        //对属性取别名
        xStream.aliasField("省", Address.class,"province");
    }
    
    //xml转java对象
    public static Object xmlToBean(String xml){
        return xStream.fromXML(xml);
    }
    
    //java对象转xml
    public static String beanToXml(Object obj){
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xStream.toXML(obj);
    }
}

测试用例:

package com.test.test;

import java.util.ArrayList;
import java.util.List;

import com.cn.entity.Address;
import com.cn.entity.Person;
import com.cn.util.XStreamUtil;

public class TestXStream {

    public static void main(String[] args) {
        long time1  = System.currentTimeMillis();
        //测试java对象转xml,java对象中包含集合对象
        Person person = new Person();
        person.setName("admin管理员");
        person.setSex("男");
        person.setAge(25);
        List<Address> adds = new ArrayList<Address>();
        Address address1 = new Address();
        address1.setCountry("中国");
        address1.setProvince("安徽");
        address1.setCity("宿州");
        address1.setCounty("萧县");
        Address address2 = new Address();
        address2.setCountry("中国");
        address2.setProvince("上海");
        address2.setCity(null);
        address2.setCounty("");
        adds.add(address1);
        adds.add(address2);
        person.setAddress(adds);
        String xml = XStreamUtil.beanToXml(person);
        System.out.println(xml);
        
        //测试xml转java对象
        Person person2 = (Person) XStreamUtil.xmlToBean(xml);
        System.out.println(person2.getAddress().get(1).getProvince());
        
        long time2 = System.currentTimeMillis();
        System.out.println((time2-time1)+"ms");
    }
}

执行后控制台打印:

<?xml version="1.0" encoding="UTF-8"?>
<person>
  <name>admin管理员</name>
  <sex></sex>
  <age>25</age>
  <Address>
    <address country="中国">
      <>安徽</>
      <city>宿州</city>
      <county>萧县</county>
    </address>
    <address country="中国">
      <>上海</>
      <county></county>
    </address>
  </Address>
</person>
上海
669ms

总结:

   (1) XStream是一个可以将javaBean与XML双向转换的java类库。

   (2) Java到xml,使用toXML()方法;xml到Java,用fromXML()方法。

   (3) 类别名,用alias(String name, Class type)。

   (4) 类成员别名,用aliasField(String alias, Class definedIn, String fieldName)。

   (5) 将某一个类的属性,作为xml头信息的属性,而不是子节点,用useAttributeFor(Class definedIn, String fieldName)。

   (5) 类成员作为属性别名,用 aliasAttribute(Class definedIn, String attributeName, String alias),单独命名没有意义,还要通过useAttributeFor(Class definedIn, String fieldName) 应用到某个类上。

   (6) XStream默认当String类型的属性值为null时不封装到xml中。可以根据实际传xml情况,选择对象属性set空字符串还是null。

posted @ 2016-08-13 01:37  彩虹过后的羽翼  阅读(450)  评论(0编辑  收藏  举报