ToAttributedValueConverter
我可以通过在NumberOfPersonnel
类和@XStreamImplicit
List-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>