-
介绍
XStream是一个很方便的XML和Bean对象之间转换的工具。
- 简单示例
添加如下maven依赖:
<pre class="lang:default decode:true "><dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.10</version>
</dependency></pre>
代码如下:
<pre class="lang:default decode:true ">package com.surenpi.autotest;
import com.thoughtworks.xstream.XStream;
/**
-
xstream的简单使用示例
-
@author suren
*/
public class Test {
public static void main(String[] args) {
XStream xStream = new XStream();
xStream.alias("person", Person.class);
xStream.useAttributeFor(Person.class, "name");
xStream.aliasField("myAge", Person.class, "age");Person person = new Person(); person.setName("name"); person.setAge(12); String xml = xStream.toXML(person); System.out.println(xml); Object result = xStream.fromXML(xml); System.out.println(result);
}
}</pre>
通过上面的示例,我们可以完成一些简单的xml和bean对象之间的互相转换。如果实际项目中,需要有一些特定的转换,例如要在XML中添加大段的文本,可以采用下面的方式:
<pre class="lang:default decode:true crayon-selected">package com.surenpi.autotest;
import com.thoughtworks.xstream.XStream;
/**
-
xstream的简单使用示例
-
@author suren
*/
public class Test {
public static void main(String[] args) {
XStream xStream = new XStream();
xStream.alias("person", Person.class);
xStream.useAttributeFor(Person.class, "name");
xStream.aliasField("myAge", Person.class, "age");
xStream.registerLocalConverter(Person.class, "remark",
new TextConverter()); //自定义类型转换Person person = new Person(); person.setName("name"); person.setAge(12); person.setRemark("remark"); String xml = xStream.toXML(person); System.out.println(xml); Object result = xStream.fromXML(xml); System.out.println(result);
}
}</pre> -
参考
本文为原创,如果您当前访问的域名不是surenpi.com,请访问“素人派”。
网友评论