我正在使用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类和读取它的代码进行建模,如下所示--
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中的属性列表始终为空,即使我在这两种情况下使用相同的技术。有没有人能帮忙解决这个问题。在这方面的帮助是非常感谢的。
发布于 2012-10-02 00:11:45
您的XML格式与Java对象模型不匹配。根据XML,<Property>是<Objects>的子类,但是根据您的代码,Properties列表是ResponseObject的一部分。您需要修复此不匹配。
而且,您似乎混合使用了注释和代码。要么只使用注释(推荐),要么全部用代码完成。否则,您的代码将变得混乱和不可读。
更新:
我看到你已经修复了你的XML。问题是您的ResponseObject中有一个Value字段,但xml元素中没有值,因此请删除它。
下面的代码应该可以工作:
@XStreamAlias("Objects")
public class ParentResponseObject {
@XStreamImplicit
List<ResponseObject> responseObjects = new ArrayList<ResponseObject>();
}
@XStreamAlias("Object")
public class ResponseObject {
@XStreamAsAttribute
String Type;
@XStreamImplicit
List<Properties> properties = new ArrayList<Properties>();
}
@XStreamAlias("Property")
@XStreamConverter(value = ToAttributedValueConverter.class, strings = { "Value" })
public class Properties {
String Name;
String Type;
String Value;
}Main方法:
XStream s = new XStream(new DomDriver());
s.processAnnotations(ParentResponseObject.class);
ParentResponseObject gh = (ParentResponseObject) s.fromXML(xml);
for (ResponseObject o : gh.responseObjects) {
System.out.println(o.Type);
for (Properties p : o.properties) {
System.out.println(p.Name + ":" + p.Type + ":" + p.Value);
}
}https://stackoverflow.com/questions/12676638
复制相似问题