Reading XML value to populate Java variable

六月ゝ 毕业季﹏ 提交于 2019-12-11 00:49:10

问题


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>

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() {

    }
}

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);

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.


回答1:


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;
    }
}

Main method:

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


来源:https://stackoverflow.com/questions/12672541/reading-xml-value-to-populate-java-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!