java - XStream 隐式集合配置问题

标签 java xml xstream

我正在使用一个生成这种类型的 XML 的系统:

<address>
  <addressLine>123 Main Street</addressLine>
  <addressLine>Suite 123</addressLine>
  <city>Test City</city>
  <stateOrProvince>AA</stateOrProvince>
  <postalCode>00000</postalCode>
</address>

这两个 addressLine 元素应该是 XStream 隐式集合的一部分 - 我想调用一个 getAddressLine()方法并得到一个List<String>输出。

我一直在使用 XStream 的教程,但还没有完全弄清楚如何获得 addressLine要正确映射的元素。 XStream's Tweaking Output tutorial 中有一个类似的用例,但没有提供示例代码:

Another use case are collections, arrays and maps. If a class has a field that is a one of those types, by default all of its elements are embedded in an element that represents the container object itself. By configuring the XStream with the XStream.addImplicitCollection(), XStream.addImplicitArray(), and XStream.addImplicitMap() methods it is possible to keep the elements directly as child of the class and the surrounding tag for the container object is omitted. It is even possible to declare more than one implicit collection, array or map for a class, but the elements must then be distinguishable to populate the different containers correctly at deserialization.

In the following example the Java type representing the farm may have two containers, one for cats and one for dogs:

<farm>
  <cat>Garfield</cat>
  <cat>Arlene</cat>
  <cat>Nermal</cat>
  <dog>Odie</dog>
</farm>

然而,这 SO answer表明 XStream 农场示例是不可能的。

我已尝试使用此 Java 代码对我的 Java 代码进行单元测试,但还没有成功:

XStream xstream = new XStream(new StaxDriver());        
xstream.alias("address", Address.class);
xstream.alias("addressLine", String.class);     
xstream.addImplicitCollection(Address.class, "addressLines");       

Address address = (Address) xstream.fromXML( 
    new FileInputStream("src/test/resources/addressTest.xml"));

还有我应该尝试的任何其他配置更改吗?

注意:我目前使用的是 XStream v1.2.2。

最佳答案

首先,如果可能,您应该升级到更新的 XStream - 1.2.2 于 2007 年发布。但要回答您的问题,请尝试:

XStream xstream = new XStream(new StaxDriver());
xstream.alias("address", Address.class);
xstream.addImplicitCollection(Address.class, "addressLines", "addressLine", String.class);

这表示将名称为 addressLine 的所有元素都视为字符串,并将它们收集到 addressLines 集合中(即 someAddress.getAddressLines() ).

关于java - XStream 隐式集合配置问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12681397/

相关文章:

java - 制作三个轻度相关类的数组

xml - 如何将参数值传递给 XSL?

java - xstream,如何将列表序列化为xml

java - 使用 Xstream,需要说明

java - XStream 如何选择其转换器?

java - java中有类似module.export的东西吗?

java - RealmModel 实现类需要仅通过 getter/setter 使用的字段吗?

java - 如何构造一个类,其变量对于大多数对象具有几乎相同的值

java - 如何从org.jdom.Document中的xml对象获取数据?

php - 如何在 rss feed 的 <description> 标签中显示链接