2

我正在使用 xstream 将一些 XML 转换为 Java 对象。XML 模式具有以下格式:

<Objects>   
<Object Type="System.Tuning" >4456</Object> 
<Object Type="System.Lag" >7789</Object>    
</Objects>

基本上,父对象标签可以有 n 个对象标签。为此,我对我的班级进行了这样的建模:

class ParentResponseObject {    
    List <ResponseObject>responseObjects = new ArrayList<ResponseObject>();
    public ParentResponseObject() {
        // TODO Auto-generated constructor stub
    }
}
class ResponseObject {
       String Type;
       String Value;
    public ResponseObject() {

    }
}

最后我使用下面的代码来填充我的 java 类:

XStream s = new XStream(new DomDriver());
  s.alias("Objects", src.core.PowerShell.MyAgain.ParentResponseObject.class);
  s.alias("Object", src.core.PowerShell.MyAgain.ResponseObject.class);  
  s.useAttributeFor(src.core.PowerShell.MyAgain.ResponseObject.class, "Type");  
        s.addImplicitCollection(src.core.PowerShell.MyAgain.ParentResponseObject.class, "responseObjects");     
        ParentResponseObject gh =(ParentResponseObject)s.fromXML(k1);

使用该useAttribute方法我能够读取对象类型的“类型”属性,但是如何读取 4456、7789 等标签中的值并将其填充到变量ResponseObject.value 中。

4

1 回答 1

2

您需要使用ToAttributedValueConverter. 使用 xstream 注释很容易做到这一点,如下所示:

@XStreamAlias("Object")
@XStreamConverter(value = ToAttributedValueConverter.class, strings = { "value" })
public class ResponseObject {

    @XStreamAlias("Type")
    private String type;

    private String value;

    public ResponseObject() {
    }

    public String getType() {
        return type;
    }

    public String getValue() {
        return value;
    }
}

@XStreamAlias("Objects")
public class ParentResponseObject {

    @XStreamImplicit
    private final List <ResponseObject> responseObjects = new ArrayList<ResponseObject>();

    public ParentResponseObject() {
    }

    public List<ResponseObject> getResponseObjects() {
        return responseObjects;
    }
}

主要方法:

XStream xStream = new XStream();
xStream.processAnnotations(ParentResponseObject.class);
ParentResponseObject parent = (ParentResponseObject)xStream.fromXML(file);
for (ResponseObject o : parent.getResponseObjects()) {
    System.out.println(o.getType() + ":" + o.getValue());
}
于 2012-10-01T12:05:50.853 回答