XStream转换xml

在工作中,总会遇到xml转换成java对象  java对象转换成xml。而一般使用的都是xStream框架来实现的。

看文档说,xStream也支持json的转换,不过,json-lib框架和jackson框架对json格式转换已经很完美了。


代码举例:

1.

通过XStream对象的toXML方法就可以完成Java对象到XML的转换,toXML方法还有2个相同签名的方法,需要传递一个流。然后通过流来完成xml信息的输出。

package com.hoo.test;
 
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.jettison.json.JSONException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.hoo.entity.Birthday;
import com.hoo.entity.Classes;
import com.hoo.entity.ListBean;
import com.hoo.entity.Student;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.json.JsonWriter;
 
/**
 * <b>function:</b>Java对象和XML字符串的相互转换
 * jar-lib-version: xstream-1.3.1
 * @author hoojo
 * @createDate Nov 27, 2010 12:15:15 PM
 * @file XStreamTest.java
 * @package com.hoo.test
 * @project WebHttpUtils
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@SuppressWarnings("unchecked")
public class XStreamTest {
    
    private XStream xstream = null;
    private ObjectOutputStream  out = null;
    private ObjectInputStream in = null;
    
    private Student bean = null;
    
    /**
     * <b>function:</b>初始化资源准备
     * @author hoojo
     * @createDate Nov 27, 2010 12:16:28 PM
     */
    @Before
    public void init() {
        try {
            xstream = new XStream();
            //xstream = new XStream(new DomDriver()); // 需要xpp3 jar
        } catch (Exception e) {
            e.printStackTrace();
        }
        bean = new Student();
        bean.setAddress("china");
        bean.setEmail("jack@email.com");
        bean.setId(1);
        bean.setName("jack");
        Birthday day = new Birthday();
        day.setBirthday("2010-11-22");
        bean.setBirthday(day);
    }
    
    /**
     * <b>function:</b>释放对象资源
     * @author hoojo
     * @createDate Nov 27, 2010 12:16:38 PM
     */
    @After
    public void destory() {
        xstream = null;
        bean = null;
        try {
            if (out != null) {
                out.flush();
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.gc();
    }
    
    public final void fail(String string) {
        System.out.println(string);
    }
    
    public final void failRed(String string) {
        System.err.println(string);
    }
}

需要的JavaBean

package com.hoo.entity;
 
public class Student {
    private int id;
    private String name;
    private String email;
    private String address;
    private Birthday birthday;
    //getter、setter
    public String toString() {
        return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
    }
}

Java转换成XML

1.javabean转换成xml

/**
 * <b>function:</b>Java对象转换成XML字符串
 * @author hoojo
 * @createDate Nov 27, 2010 12:19:01 PM
 */
@Test
public void writeBean2XML() {
    try {
        fail("------------Bean->XML------------");
        fail(xstream.toXML(bean));
        fail("重命名后的XML");
        //类重命名
        //xstream.alias("account", Student.class);
        //xstream.alias("生日", Birthday.class);
        //xstream.aliasField("生日", Student.class, "birthday");
        //xstream.aliasField("生日", Birthday.class, "birthday");
        //fail(xstream.toXML(bean));
        //属性重命名
        xstream.aliasField("邮件", Student.class, "email");
        //包重命名
        xstream.aliasPackage("hoo", "com.hoo.entity");
        fail(xstream.toXML(bean));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
运行后的结果如下:

------------Bean->XML------------
<com.hoo.entity.Student>
  <id>1</id>
  <name>jack</name>
  <email>jack@email.com</email>
  <address>china</address>
  <birthday>
    <birthday>2010-11-22</birthday>
  </birthday>
</com.hoo.entity.Student>
重命名后的XML
<hoo.Student>
  <id>1</id>
  <name>jack</name>
  <邮件>jack@email.com</邮件>
  <address>china</address>
  <birthday>
    <birthday>2010-11-22</birthday>
  </birthday>
</hoo.Student>
2、 将List集合转换成xml文档

/**
 * <b>function:</b>将Java的List集合转换成XML对象
 * @author hoojo
 * @createDate Nov 27, 2010 12:20:07 PM
 */
@Test
public void writeList2XML() {
    try {
        //修改元素名称
        xstream.alias("beans", ListBean.class);
        xstream.alias("student", Student.class);
        fail("----------List-->XML----------");
        ListBean listBean = new ListBean();
        listBean.setName("this is a List Collection");
        
        List<Object> list = new ArrayList<Object>();
        list.add(bean);
        list.add(bean);//引用bean
        //list.add(listBean);//引用listBean,父元素
        
        bean = new Student();
        bean.setAddress("china");
        bean.setEmail("tom@125.com");
        bean.setId(2);
        bean.setName("tom");
        Birthday day = new Birthday("2010-11-22");
        bean.setBirthday(day);
        
        list.add(bean);
        listBean.setList(list);
        
        //将ListBean中的集合设置空元素,即不显示集合元素标签
        //xstream.addImplicitCollection(ListBean.class, "list");
        
        //设置reference模型
        //xstream.setMode(XStream.NO_REFERENCES);//不引用
        xstream.setMode(XStream.ID_REFERENCES);//id引用
        //xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);//绝对路径引用
          
        //将name设置为父类(Student)的元素的属性
        xstream.useAttributeFor(Student.class, "name");
        xstream.useAttributeFor(Birthday.class, "birthday");
        //修改属性的name
        xstream.aliasAttribute("姓名", "name");
        xstream.aliasField("生日", Birthday.class, "birthday");
      
        fail(xstream.toXML(listBean));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

上面的代码运行后,结果如下:

----------List-->XML----------
<beans id="1">
  <name>this is a List Collection</name>
  <list id="2">
    <student id="3" 姓名="jack">
      <id>1</id>
      <email>jack@email.com</email>
      <address>china</address>
      <birthday id="4" 生日="2010-11-22"/>
    </student>
    <student reference="3"/>
    <student id="5" 姓名="tom">
      <id>2</id>
      <email>tom@125.com</email>
      <address>china</address>
      <birthday id="6" 生日="2010-11-22"/>
    </student>
  </list>
</beans>

注:

如果不加

xstream.addImplicitCollection(ListBean.class, "list");

这个设置的话,会出现一个List节点包裹着Student节点元素。添加addImplicitCollection可以忽略这个list节点元素。那么上面的list节点就不存在,只会在beans元素中出现name、student这2个xml元素标签;

setMode是设置相同的对象的引用方式,如果设置XStream.NO_REFERENCES就是不引用,会输出2分相同的Student元素。如果是XStream.ID_REFERENCES会引用相同的那个对象的id属性,如果是XStream.XPATH_ABSOLUTE_REFERENCES引用,那么它将显示xpath路径。上面采用的id引用,<student reference="3"/>这个引用了id=3的那个student标签元素;

useAttributeFor是设置某个节点显示到父节点的属性中,也就是将指定class中的指定属性,在这个class元素节点的属性中显示。

如:<student><name>hoojo</name></student>

设置好后就是这样的结果:<student name=”hoojo”></student>

aliasAttribute是修改属性名称。

3、 在JavaBean中添加Annotation注解进行重命名设置、Map集合转换xml文档、 用OutStream输出流写XML

这部分在工作中没有用到,暂时不做记载,如若用到,会参考:http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html   中内容



XML内容转换Java对象


/**
 * <b>function:</b>将XML字符串转换成Java对象
 * @author hoojo
 * @createDate Nov 27, 2010 2:39:06 PM
 */
@Test
public void readXml2Object() {
    try {
        failRed("-----------Xml >>> Bean--------------");
        Student stu = (Student) xstream.fromXML(xstream.toXML(bean));
        fail(stu.toString());
        
        List<Student> list = new ArrayList<Student>();
        list.add(bean);//add
        
        Map<String, Student> map = new HashMap<String, Student>();
        map.put("No.1", bean);//put
        
        bean = new Student();
        bean.setAddress("china");
        bean.setEmail("tom@125.com");
        bean.setId(2);
        bean.setName("tom");
        Birthday day = new Birthday("2010-11-22");
        bean.setBirthday(day);
        list.add(bean);//add
        map.put("No.2", bean);//put
        
        bean = new Student();
        bean.setName("jack");
        list.add(bean);//add
        map.put("No.3", bean);//put
        
        failRed("==========XML >>> List===========");
        List<Student> studetns = (List<Student>) xstream.fromXML(xstream.toXML(list));
        fail("size:" + studetns.size());//3
        for (Student s : studetns) {
            fail(s.toString());
        }
        
        failRed("==========XML >>> Map===========");
        Map<String, Student> maps = (Map<String, Student>) xstream.fromXML(xstream.toXML(map));
        fail("size:" + maps.size());//3
        Set<String> key = maps.keySet();
        Iterator<String> iter = key.iterator();
        while (iter.hasNext()) {
            String k = iter.next();
            fail(k + ":" + map.get(k));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

运行后结果如下:

-----------Xml >>> Bean--------------
jack#1#china#2010-11-22#jack@email.com
==========XML >>> List===========
size:3
jack#1#china#2010-11-22#jack@email.com
tom#2#china#2010-11-22#tom@125.com
jack#0#null#null#null
==========XML >>> Map===========
size:3
No.3:jack#0#null#null#null
No.1:jack#1#china#2010-11-22#jack@email.com
No.2:tom#2#china#2010-11-22#tom@125.com


2. 用InputStream将XML文档转换成java对象

具体内容见:http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html

xStream对json的支持

具体内容见:http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值