2013-07-12 32 views
1

的XML我想转换的样子:XStream的:采集转换与属性

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

按照XSD,可以有多个这些标签的,所以这是一个集合。生成的代码看起来像:

protected List<NumberOfPersonnel> numberOfEmployees; 

当我使用@XStreamImplicit,则丢弃该值,所以我需要一个转换器。但将@XStreamImplicit@XStreamConverter结合似乎不起作用。

那么我该如何做到这一点?我试着用我自己的自定义转换器从CollectionConverter继承,但它声称不会找到任何孩子,老实说,我不知道我在做什么。

有人能教导我吗?这不应该这么难,应该吗?

回答

2

我可以把它通过在列表值属性使用ToAttributedValueConverterNumberOfPersonnel类和@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> 
+0

谢谢你!这正是我所需要的,比我想要的更优雅。它看起来像一个同事写的所有定制转换器是不必要的,应该用这个替换。 – mcv