-
介紹
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> -
參考
本文為原創(chuàng),如果您當前訪問的域名不是surenpi.com痹雅,請訪問“素人派”。