gpt4 book ai didi

java - 读取 XML 值以填充 Java 变量

转载 作者:行者123 更新时间:2023-11-30 09:32:00 25 4
gpt4 key购买 nike

我正在使用 xstream 将一些 XML 转换为 Java 对象。 XML 模式的格式如下:

<Objects>   
<Object Type="System.Tuning" >4456</Object>
<Object Type="System.Lag" >7789</Object>
</Objects>

基本上,父 Objects 标签可以有 n 个 Object 标签。为此,我像这样模拟了我的类(class):

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.

最佳答案

您需要使用 ToAttributedValueConverter .使用 xstream 注释很容易做到这一点,如下所示:

@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());
}

关于java - 读取 XML 值以填充 Java 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12672541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com