1. 初始化要转为 XML 的数据:
// 生成第一条地址数据; Address address1 = new Address(1, "地址一", "广东省XX市", "XX公司"); // 生成第二条地址数据; Address address2 = new Address(2, "地址二", "广东省XX市", "家"); List<Address> addresses = new ArrayList<Address>(); // 将生成的地址数据放到 List 中; addresses.add(address1); addresses.add(address2); // 生成 People 对象并制定相应数据; People people = new People(1, "Shawearn", 1, addresses);
// 新建 XStream 对象; XStream xStream = new XStream(); // 将 People 类的示例转化为 XML 格式的字符串; String xmlStr = xStream.toXML(people); // 打印输出转化后的 XML 字符串; System.out.println(xmlStr);运行结果
<com.shawearn.sitmap.People> <id>1</id> <name>Shawearn</name> <age>1</age> <addresses> <com.shawearn.xml.Address> <id>1</id> <name>地址一</name> <address>广东省XX市</address> <desc>XX公司</desc> </com.shawearn.xml.Address> <com.shawearn.xml.Address> <id>2</id> <name>地址二</name> <address>广东省XX市</address> <desc>家</desc> </com.shawearn.xml.Address> </addresses> </com.shawearn.xml.People>我们会发现节点名字使用了类名,此时可以用 alias 指定 Java 类对应的节点名该方法需要在调用 toXML() 方法之前使用:
/** * Alias a Class to a shorter name to be used in XML elements. * * @param name Short name * @param type Type to be aliased * @throws InitializationException if no {@link ClassAliasingMapper} is available */ public void alias(String name, Class type);
// 指定 People 类对应的节点名为 People; xStream.alias(People.class.getSimpleName(), People.class); // 指定 Address 类对应的节点名为 address; xStream.alias("address", Address.class);指定别名后的运行结果:
<People> <id>1</id> <name>Shawearn</name> <age>1</age> <addresses> <address> <id>1</id> <name>地址一</name> <address>广东省XX市</address> <desc>XX公司</desc> </address> <address> <id>2</id> <name>地址二</name> <address>广东省XX市</address> <desc>家</desc> </address> </addresses> </People>
3. XML 转化为 Java 对象;
// 新建 XStream 对象; XStream s = new XStream(); // 指定 People 类对应的节点名为 People; s.alias(People.class.getSimpleName(), People.class); // 指定 Address 类对应的节点名为 address; s.alias("address", Address.class); // 将 XML 字符串转化为 People 对象; People people2 = (People) s.fromXML(xmlStr); // 打印输出转化后的 People 对象; System.out.println(people2.toString());
People [id=1, name=Shawearn, age=1, addresses=[Address [id=1, name=地址一, address=广东省XX市, desc=XX公司], Address [id=2, name=地址二, address=广东省XX市, desc=家]]]