XStream:使用属性转换集合

时间:2013-07-12 13:32:34

标签: xstream

我试图转换的XML看起来像:

<numberOfEmployees year="2013">499.0</numberOfEmployees>

根据XSD,可以有多个这样的标签,所以它是一个集合。生成的代码如下所示:

    protected List<NumberOfPersonnel> numberOfEmployees;

当我使用@XStreamImplicit时,它会丢弃值,所以我需要一个转换器。但将@XStreamImplicit@XStreamConverter合并似乎无效。

那我该怎么做?我已经尝试使用继承自CollectionConverter的我自己的自定义转换器,但它声称没有找到任何孩子,老实说我不知道​​我在做什么。

有人可以开导我吗?这应该不是这么难,不是吗?

1 个答案:

答案 0 :(得分:2)

我可以使用NumberOfPersonnel类上的ToAttributedValueConverter和列表值属性上的@XStreamImplicit来使其工作:

<强> NumberOfPersonnel.java

import com.thoughtworks.xstream.annotations.*;
import com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter;

// treat the "value" property as the element content and all others as attributes
@XStreamConverter(value = ToAttributedValueConverter.class, strings = {"value"})
public class NumberOfPersonnel {
  public NumberOfPersonnel(int year, double value) {
    this.year = year;
    this.value = value;
  }

  private int year;

  private double value;

  public String toString() {
    return year + ": " + value;
  }
}

<强> Container.java

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.*;
import java.util.List;
import java.util.Arrays;
import java.io.File;

@XStreamAlias("container")
public class Container {
  private String name;

  // any element named numberOfEmployees should go into this list
  @XStreamImplicit(itemFieldName="numberOfEmployees")
  protected List<NumberOfPersonnel> numberOfEmployees;

  public Container(String name, List<NumberOfPersonnel> noEmp) {
    this.name = name;
    this.numberOfEmployees = noEmp;
  }

  public String toString() {
    return name + ", " + numberOfEmployees;
  }

  public static void main(String[] args) throws Exception {
    XStream xs = new XStream();
    xs.processAnnotations(Container.class);

    System.out.println("Unmarshalling:");
    System.out.println(xs.fromXML(new File("in.xml")));

    System.out.println("Marshalling:");
    System.out.println(xs.toXML(new Container("World",
           Arrays.asList(new NumberOfPersonnel(2001, 1000),
                         new NumberOfPersonnel(2002, 500)))));
  }
}

<强> in.xml

<container>
  <name>Hello</name>
  <numberOfEmployees year="2013">499.0</numberOfEmployees>
  <numberOfEmployees year="2012">550.0</numberOfEmployees>
</container>

<强>输出

Unmarshalling:
Hello, [2013: 499.0, 2012: 550.0]
Marshalling:
<container>
  <name>World</name>
  <numberOfEmployees year="2001">1000.0</numberOfEmployees>
  <numberOfEmployees year="2002">500.0</numberOfEmployees>
</container>