1

我尝试转换的 XML 如下所示:

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

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

    protected List<NumberOfPersonnel> numberOfEmployees;

当我使用@XStreamImplicit时,它会降低价值,所以我需要一个转换器。但结合@XStreamImplicitwith@XStreamConverter似乎不起作用。

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

有人可以启发我吗?这不应该这么难,不是吗?

4

1 回答 1

2

ToAttributedValueConverter我可以通过在NumberOfPersonnel类和@XStreamImplicitList-valued 属性上使用来使其工作:

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;
  }
}

容器.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)))));
  }
}

在.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>
于 2013-07-15T09:22:01.240 回答