读取 XML 值以填充 Java 变量 [英] Reading XML value to populate Java variable
问题描述
我正在使用 xstream 将一些 XML 转换为 Java 对象.XML 模式的格式如下:
I am working with xstream to convert some XML into Java objects. The XML pattern is of the below format:
<Objects>
<Object Type="System.Tuning" >4456</Object>
<Object Type="System.Lag" >7789</Object>
</Objects>
基本上父对象标签可以有 n 个对象标签.为此,我为我的班级建模:
Basically the parent Objects tag can have n number of Object tags. For this I have modelled my class like this:
class ParentResponseObject {
List <ResponseObject>responseObjects = new ArrayList<ResponseObject>();
public ParentResponseObject() {
// TODO Auto-generated constructor stub
}
}
class ResponseObject {
String Type;
String Value;
public ResponseObject() {
}
}
最后我使用下面的代码来填充我的 java 类:
And finally I am using the below code to populate my java class:
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.
Using the useAttribute
method I am able to read the "Type" attribute of Object Type, but how do I read the values within tags like 4456, 7789 and populate it in the variable ResponseObject
.value.
推荐答案
您需要使用 ToAttributedValueConverter
.使用 xstream 注释很容易做到这一点,如下所示:
You need to use the ToAttributedValueConverter
. It is easy to do this using xstream annotations as shown below:
@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());
}
这篇关于读取 XML 值以填充 Java 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!