我试图转换的XML看起来像:
<numberOfEmployees year="2013">499.0</numberOfEmployees>
根据XSD,可以有多个这样的标签,所以它是一个集合。生成的代码如下所示:
protected List<NumberOfPersonnel> numberOfEmployees;
当我使用@XStreamImplicit
时,它会丢弃值,所以我需要一个转换器。但将@XStreamImplicit
与@XStreamConverter
合并似乎无效。
那我该怎么做?我已经尝试使用继承自CollectionConverter的我自己的自定义转换器,但它声称没有找到任何孩子,老实说我不知道我在做什么。
有人可以开导我吗?这应该不是这么难,不是吗?
答案 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>