我正在使用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>
基本上在对象标签下可以有 n 个对象类型,每个对象类型可以有 n 个属性标签。所以我用Java类和代码来建模如下——
class ParentResponseObject {
List <ResponseObject>responseObjects = new ArrayList<ResponseObject>();
}
@XStreamAlias("Object")
@XStreamConverter(value = ToAttributedValueConverter.class, strings = { "Value" })
class ResponseObject {
String Type;
String Value;
List <Properties> properties = new ArrayList<Properties>();
}
@XStreamAlias("Property")
@XStreamConverter(value = ToAttributedValueConverter.class, strings = { "Value" })
class Properties {
String Name;
String Type;
String Value;
}
public class MyAgainTest {
public static void main (String[] args) throws Exception {
String k1 = //collect the xml as string
XStream s = new XStream(new DomDriver());
s.alias("Objects", ParentResponseObject.class);
s.alias("Object", ResponseObject.class);
s.alias("Property", Properties.class);
s.useAttributeFor(ResponseObject.class, "Type");
s.addImplicitCollection(ParentResponseObject.class, "responseObjects");
s.addImplicitCollection(ResponseObject.class, "properties");
s.useAttributeFor(Properties.class, "Name");
s.useAttributeFor(Properties.class, "Type");
s.processAnnotations(ParentResponseObject.class);
ParentResponseObject gh =(ParentResponseObject)s.fromXML(k1);
System.out.println(gh.toString());
}
}
使用此代码,我可以在 ParentResponseObject 类中填充 responseObjects 列表。但是,ResponseObject 中的属性列表始终为空,即使我在这两种情况下都使用相同的技术。任何人都可以帮助解决这个问题。对此的帮助非常感谢。