当前位置: 移动技术网 > IT编程>开发语言>Java > XStream使用方法总结附实例代码

XStream使用方法总结附实例代码

2017年12月12日  | 移动技术网IT编程  | 我要评论

z610i,玛杰卡,李诗韵男友

xstream中的核心类就是xstream类,一般来说,熟悉这个类基本就够用了,如果你用的更多,估计是你设计有问题,否则不需要。

xstream对象相当java对象和xml之间的转换器,转换过程是双向的。创建xsteam对象的方式很简单,只需要new xstream()即可。
java到xml,用toxml()方法。
xml到java,用fromxml()方法。

在没有任何设置默认情况下,java到xml的映射,是java成员名对应xml的元素名,java类的全名对应xml根元素的名字。而实际中,往往是xml和java类都有了,要完成相互转换,必须进行别名映射。

别名配置包含三种情况:
1、类别名,用alias(string name, class type)。
2、类成员别名,用aliasfield(string alias, class definedin, string fieldname)
3、类成员作为属性别名,用 aliasattribute(class definedin, string attributename, string alias),单独命名没有意义,还要通过useattributefor(class definedin, string fieldname) 应用到某个类上。
别名的配置是非常重要的,但是其中有些细节问题很重要,在例子中会专门做详细说明。

另外还有不太常用的方法:
addimplicitcollection(class ownertype, string fieldname),去掉集合类型生成xml的父节点。
registerconverter(converter converter) ,注册一个转换器。

如果你的xml很大,或者为了安全性,以流的方式传输,那么xstream也提供丰富的api,
使用起来也非常简便。目前还用不到,暂不考虑。

如果这些基本的操作还不能满足你应用的需求,xstream提供丰富的扩展点。你可以实现自己的转换器。还可以利用xstream完成更负责的功能,比如输出其他非xml格式的数据,还可以输出html,还支持xml dom类型数据,这些应用起来稍微复杂些。当然这些不是xstream应用的重点,也不用理会,真正需要的时候再查看api和源码研究研究。

xstream的优点很多,但是也有一些小bug,比如在定义别名中的下划线“_”转换为xml后会变成“__”这个符号,很变态。因此,尽量避免在别名中实用任何符号,却是需要下划线的时候,可以考虑实用连接符“-”,这个没有问题。

另外,我们的java bean中,常常有一些常量,在转换过程,xstream也会将这些常量转换过去,形成常量的xml节点,这显然不是想要的结果,对于常量字段,就不做转换了。

 
下面给出一个非常典型的而且实用的例子,作为对总结的补充:
package test; 

import java.util.list; 

/** 
* created by intellij idea.<br> 
* <b>user</b>: leizhimin<br> 
* <b>date</b>: 2008-5-22 21:10:13<br> 
* <b>note</b>: please add comment here! 
*/ 
public class person { 
    private string name; 
    private string age; 
    private profile profile; 
    private list<address> addlist; 

    public person(string name, string age, profile profile, list<address> addlist) { 
        this.name = name; 
        this.age = age; 
        this.profile = profile; 
        this.addlist = addlist; 
    } 

    public string tostring() { 
        return "person{" + 
                "name='" + name + '\'' + 
                ", age='" + age + '\'' + 
                ", profile=" + profile + 
                ", addlist=" + addlist + 
                '}'; 
    } 
}

package test; 

import java.sql.date; 

/** 
* created by intellij idea.<br> 
* <b>user</b>: leizhimin<br> 
* <b>date</b>: 2008-5-22 21:10:32<br> 
* <b>note</b>: please add comment here! 
*/ 
public class profile { 
    private string job; 
    private string tel; 
    private string remark; 

    public profile(string job, string tel, string remark) { 
        this.job = job; 
        this.tel = tel; 
        this.remark = remark; 
    } 

    public string tostring() { 
        return "profile{" + 
                "job='" + job + '\'' + 
                ", tel='" + tel + '\'' + 
                ", remark='" + remark + '\'' + 
                '}'; 
    } 
}

package test; 

/** 
* created by intellij idea.<br> 
* <b>user</b>: leizhimin<br> 
* <b>date</b>: 2008-5-22 21:10:22<br> 
* <b>note</b>: please add comment here! 
*/ 
public class address { 
    private string add; 
    private string zipcode; 

    public address(string add, string zipcode) { 
        this.add = add; 
        this.zipcode = zipcode; 
    } 


    public string tostring() { 
        return "address{" + 
                "add='" + add + '\'' + 
                ", zipcode='" + zipcode + '\'' + 
                '}'; 
    } 
}

package test; 

import com.thoughtworks.xstream.xstream; 

import java.util.list; 
import java.util.arraylist; 

/** 
* created by intellij idea.<br> 
* <b>user</b>: leizhimin<br> 
* <b>date</b>: 2008-5-22 21:10:47<br> 
* <b>note</b>: xstream学习[http://lavasoft.blog.51cto.com] 
*/ 
public class testxstream { 

    public static void main(string args[]) { 
        test(); 
    } 

    public static void test() { 
        system.out.println("----------xstream学习:http://lavasoft.blog.51cto.com----------"); 
        //目标对象 
        address address1 = new address("郑州市经三路", "450001"); 
        address address2 = new address("西安市雁塔路", "710002"); 
        list<address> addlist = new arraylist<address>(); 
        addlist.add(address1); 
        addlist.add(address2); 
        profile profile = new profile("软件工程师", "13512129933", "备注说明"); 
        person person = new person("熔岩", "27", profile, addlist); 

        //转换装配 
        xstream xstream = new xstream(); 

        /**************    设置类别名   ****************/ 
        xstream.alias("person", test.person.class); 
        xstream.alias("profile", test.profile.class); 
        xstream.alias("address", test.address.class); 
        output(1, xstream, person); 

        /*************  设置类成员的别名 ***************/ 
        //设置person类的name成员别名name 
        xstream.aliasfield("name", person.class, "name"); 
        /*[注意] 设置person类的profile成员别名profile,这个别名和profile类的别名一致, 
         * 这样可以保持xstream对象可以从profile成员生成的xml片段直接转换为profile成员, 
         * 如果成员profile的别名和profile的别名不一致,则profile成员生成的xml片段不可 
         * 直接转换为profile对象,需要重新创建xstream对象,这岂不给自己找麻烦?       */ 
        xstream.aliasfield("profile", test.person.class, "profile"); 
        xstream.aliasfield("addlist", test.person.class, "addlist"); 
        xstream.aliasfield("add", test.address.class, "add"); 
        xstream.aliasfield("job", test.profile.class, "job"); 
        output(2, xstream, person); 

        /*******  设置类成员为xml一个元素上的属性 *******/ 
        xstream.useattributefor(address.class, "zipcode"); 
        /*************  设置属性的别名 ***************/ 
        xstream.aliasattribute(test.address.class, "zipcode", "zipcode"); 
        output(3, xstream, person); 

        /*************  将xml转为java对象 ******×****/ 
        string person_xml = "<person>\n" + 
                "  <name>熔岩</name>\n" + 
                "  <age>27</age>\n" + 
                "  <profile>\n" + 
                "    <job>软件工程师</job>\n" + 
                "    <tel>13512129933</tel>\n" + 
                "    <remark>备注说明</remark>\n" + 
                "  </profile>\n" + 
                "  <addlist>\n" + 
                "    <address zipcode=\"450001\">\n" + 
                "      <add>郑州市经三路</add>\n" + 
                "    </address>\n" + 
                "    <address zipcode=\"710002\">\n" + 
                "      <add>西安市雁塔路</add>\n" + 
                "    </address>\n" + 
                "  </addlist>\n" + 
                "</person>"; 
        string profile_xml = "  <profile>\n" + 
                "    <job>软件工程师</job>\n" + 
                "    <tel>13512129933</tel>\n" + 
                "    <remark>备注说明</remark>\n" + 
                "  </profile>"; 
        string address_xml = "    <address zipcode=\"710002\">\n" + 
                "      <add>西安市雁塔路</add>\n" + 
                "    </address>"; 

        //同样实用上面的xstream对象xstream 
        system.out.println(xstream.fromxml(person_xml).tostring()); 
        system.out.println(xstream.fromxml(profile_xml).tostring()); 
        system.out.println(xstream.fromxml(address_xml).tostring()); 
    } 

    public static void output(int i, xstream xstream, object obj) { 
        string xml = xstream.toxml(obj); 
        system.out.println(">>>第[ " + i + "]次输出\n"); 
        system.out.println(xml + "\n"); 
    } 
}

----------xstream学习:http://lavasoft.blog.51cto.com---------- 
>>>第[ 1]次输出 

<person> 
  <name>熔岩</name> 
  <age>27</age> 
  <profile> 
    <job>软件工程师</job> 
    <tel>13512129933</tel> 
    <remark>备注说明</remark> 
  </profile> 
  <addlist> 
    <address> 
      <add>郑州市经三路</add> 
      <zipcode>450001</zipcode> 
    </address> 
    <address> 
      <add>西安市雁塔路</add> 
      <zipcode>710002</zipcode> 
    </address> 
  </addlist> 
</person> 

>>>第[ 2]次输出 

<person> 
  <name>熔岩</name> 
  <age>27</age> 
  <profile> 
    <job>软件工程师</job> 
    <tel>13512129933</tel> 
    <remark>备注说明</remark> 
  </profile> 
  <addlist> 
    <address> 
      <add>郑州市经三路</add> 
      <zipcode>450001</zipcode> 
    </address> 
    <address> 
      <add>西安市雁塔路</add> 
      <zipcode>710002</zipcode> 
    </address> 
  </addlist> 
</person> 

>>>第[ 3]次输出 

<person> 
  <name>熔岩</name> 
  <age>27</age> 
  <profile> 
    <job>软件工程师</job> 
    <tel>13512129933</tel> 
    <remark>备注说明</remark> 
  </profile> 
  <addlist> 
    <address zipcode="450001"> 
      <add>郑州市经三路</add> 
    </address> 
    <address zipcode="710002"> 
      <add>西安市雁塔路</add> 
    </address> 
  </addlist> 
</person> 

person{name='熔岩', age='27', profile=profile{job='软件工程师', tel='13512129933', remark='备注说明'}, addlist=[address{add='郑州市经三路', zipcode='450001'}, address{add='西安市雁塔路', zipcode='710002'}]} 
profile{job='软件工程师', tel='13512129933', remark='备注说明'} 
address{add='西安市雁塔路', zipcode='710002'} 

process finished with exit code 0

在实际中,类的属性很多,嵌套层次也很复杂,如果仅仅使用xstream原生api来硬编码设置别名等属性,显得太生硬也难以维护。完全可以考虑通过一个xml配置文件来定义所有用到的类的别名定义(包括其成员),然后,通过读取配置构建一个xstream的工厂,在用到时候直接去取,而不是让实用者组装。我目前的一个项目中,就是这么实现的,效果非常的好。

下面我给出针对上面提出的问题一个解决方案:

思想:考虑做一个过滤器,在xml转java之前,在java转xml之后,应用这个过滤器。这个过滤器提供将xml中的“__”替换为“-”,并且将xml中的不需要的节点剔除。
在过滤之前,我实现了个转换器装配,这一步通过xml来配置,并在java中获取。
代码就省略了,这一步很灵活,关键看你的应用了。

为了能过滤xml,我们需要用dom4j递归遍历xml文档。下面一些算法代码:

    //递归算法:遍历配置文件,找出所有有效的xpath 
    private static void recursiveelement(element element) { 
        list<element> elements = element.elements(); 
        validxpathlist.add(element.getpath()); 
        if (elements.size() == 0) { 
            //没有子元素 
        } else { 
            //有子元素 
            for (iterator<element> it = elements.iterator(); it.hasnext();) { 
                //递归遍历 
                recursiveelement(it.next()); 
            } 
        } 
    } 

    //递归算法:遍历xml,标识无效的元素节点 
    private static void recursivefixelement(element element) { 
        list<element> elements = element.elements(); 
        if (!validxpathlist.contains(element.getpath())) { 
            element.addattribute("delete", "true"); 
        } 
        if (elements.size() == 0) { 
            //没有子元素 
        } else { 
            //有子元素 
            for (iterator<element> it = elements.iterator(); it.hasnext();) { 
                element e = it.next(); 
                if (!validxpathlist.contains(e.getpath())) { 
                    e.addattribute("delete", "true"); 
                } 
                //递归遍历 
                recursivefixelement(e); 
            } 
        } 
    } 

    /** 
     * 过滤器接口方法,转换不规范字符,剔除无效节点 
     * 
     * @param xmlstr 要过滤的xml 
     * @return 符合转换器要求的xml 
     */ 
    public static string filter(string xmlstr) { 
        document document = null; 
        try { 
            document = documenthelper.parsetext(xmlstr.replaceall("__", "_")); 
            //递归的调用:标记要剔除的xml元素 
            recursivefixelement(document.getrootelement());      
            list<node> nodelist = document.selectnodes("//@delete"); 
            for (node node : nodelist) { 
                node.getparent().detach();  //剔除xml元素 
            } 
        } catch (documentexception e) { 
            system.out.println(e.getmessage()); 
            e.printstacktrace(); 
        } 
        return document.asxml(); 
    }

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网