读取XML值来填充Java变量(Reading XML value to populate Java

2019-09-23 07:03发布

我使用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的。

Answer 1:

您需要使用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());
}


文章来源: Reading XML value to populate Java variable