该实例在内部含有一个List<String>,当想把String 按照自己想要的格式显示,需要做一个小小的操作,代码如下所示:
package xstream;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import pojo.Person;
public class PersonTest
{
@Test
public void ObjectToXML()
{
Person p = new Person();
p.setAge(20);
p.setName("张三");
p.setScore(80);
List<String> list = new ArrayList<String>();
list.add("13878688599");
list.add("13475655585");
list.add("13684186587");
p.setPhones(list);
XStream stream = new XStream();
/** 声明要转的pojo类,可以试下删掉会怎么样^_^ */
stream.alias("Person", Person.class);
/** 声明要转的pojo类,可以试下删掉会怎么样^_^ */
stream.alias("number", String.class);
/** 声明要 换名字的类中属性,可以试下删掉会怎么样^_^ */
stream.aliasField("Phones", Person.class, "phones");
String s = stream.toXML(p);
System.out.println(s);
}
@Test
public void XMLToObject()
{
StringBuilder sb = new StringBuilder();
sb.append("<Person>");
sb.append("<name>张三</name>");
sb.append("<age>20</age>");
sb.append("<score>80</score>");
sb.append("<Phones><number>13878688599</number><number>13475655585</number></Phones>");
sb.append("</Person>");
/**这里面最好加入new DomDriver(),不然有异常,可以试下删掉会怎么样^_^ */
XStream stream = new XStream(new DomDriver());
/** 声明要转的pojo类,可以试下删掉会怎么样^_^ */
stream.alias("Person", Person.class);
/** 声明要转的pojo类,可以试下删掉会怎么样^_^ */
stream.alias("number", String.class);
/** 声明要 换名字的类中属性,可以试下删掉会怎么样^_^ */
stream.aliasField("Phones", Person.class, "phones");
Person p = (Person)stream.fromXML(sb.toString());
System.out.println(p.getName());
}
}