使用xstream填充列表值

时间:2012-10-03 06:11:52

标签: java xml xml-parsing xml-serialization xstream

我正在使用Xstream以下列格式阅读一些xml

 <Objects>  
  <Object Type="System.Management.Automation.Internal.Host.InternalHost">   
    <Property Name="Name" Type="System.String">ConsoleHost</Property>   
    <Property Name="Version" Type="System.Version">2.0</Property>   
    <Property Name="InstanceId" Type="System.Guid">7e2156</Property>
  </Object> 
</Objects> 

基本上在Objects标签下可以有n个Object Type,每个Object Type可以有n个Property标签。所以我用 Java 类和代码来建模,如下所示

 @XStreamAlias("Objects")
class ParentResponseObject {
    @XStreamImplicit
    List <ResponseObject>responseObjects = new ArrayList<ResponseObject>(); 
    public String toString () {
        return responseObjects.get(0).toString();       
    }   
}
@XStreamAlias("Object")
@XStreamConverter(value = ToAttributedValueConverter.class, strings = { "value" })
class ResponseObject {
    @XStreamAsAttribute
       String Type;
       String value;
       @XStreamImplicit
       List <Properties> properties = new ArrayList<Properties>();  
      public String toString () {
        return Type+" value is "+"List is "+properties+ value;      
    }   
}
@XStreamAlias("Property")
@XStreamConverter(value = ToAttributedValueConverter.class, strings = { "value" })
class Properties {
    @XStreamAsAttribute
    String Name;
    @XStreamAsAttribute
    String Type;
    String value;
    Properties (String name, String type,String value) {
            this.Name = name;
            this.Type = type;
            this.value =  value;
        }   
}

使用此代码,我可以填充responseObjects类中的ParentResponseObject列表。但是,ResponseObject中的属性列表始终为null并且未填充,即使我在两种情况下都使用相同的技术。我调试了很多但找不到任何东西。请求您的帮助和指导。

1 个答案:

答案 0 :(得分:2)

添加隐含的引用将起作用

  @XStreamImplicit(itemFieldName="Object")
  List<ResponseObject> responseObjects = new ArrayList<ResponseObject>();

  @XStreamImplicit(itemFieldName="Property")
  List<Properties> properties = new ArrayList<Properties>();