[英]Unmarshall the XML string to Java object using JAXB
我想使用JAXB将下面的XML字符串转换为Java对象。
我可以转换对象,但解组后documents
将变为null
。 Result [hits=1, tookInMillis=10, totalHits=1, documents=null]
如何更正documents
对象以获取值?
XML字串:
<result hits="1" tookInMillis="9" totalHits="1" xmlns="http://www.example.com/search/result/1.0">
<documents>
<document id="1" company="TEST" type="CN" generationDate="2018-05-24T06:05:37.000Z">
<field type="xs:string" name="test1">test1</field>
<field type="xs:string" name="test2">test2</field>
<field type="xs:string" name="test3">test3</field>
<field type="xs:string" name="test4">test4</field>
<field type="xs:string" name="test5">test5</field>
<field type="xs:string" name="test6">test6</field>
<field type="xs:string" name="test7">test7</field>
<field type="xs:string" name="test8">test8</field>
<field type="xs:date" name="date">2018-05-23</field>
</document>
</documents>
</result>
您需要注意XML名称空间。
在XML中,在XML元素中指定的名称空间(如<result>
)继承其子元素( <documents>
, <document>
和<field>
)。
在Java中则不是。 因此,您需要在子属性的@XmlElement
和@XmlElementWrapper
批注中显式地提供名称空间。
在解组XML示例时,以下Java类可以正常工作。 特别是,集合Result.documents
和Document.fields
都不为null
。
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "result", namespace = "http://www.example.com/search/result/1.0")
public class Result {
@XmlAttribute
private int hits;
@XmlAttribute
private int tookInMillis;
@XmlAttribute
private int totalHits;
@XmlElementWrapper(name = "documents", namespace = "http://www.example.com/search/result/1.0")
@XmlElement(name = "document", namespace = "http://www.example.com/search/result/1.0")
private List<Document> documents;
// ... public getters and setters (omitted for brevity)
}
@XmlAccessorType(XmlAccessType.FIELD)
public class Document {
@XmlAttribute
private int id;
@XmlAttribute
private String company;
@XmlAttribute
private String type;
@XmlAttribute
private Date generationDate;
@XmlElement(name = "field", namespace = "http://www.example.com/search/result/1.0")
private List<Field> fields;
// ... public getters and setters (omitted for brevity)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.