【发布时间】:2012-09-22 06:12:47
【问题描述】:
我正在使用 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 中。
【问题讨论】:
标签: java xml xml-parsing xml-serialization xstream