问题描述
我有一个XML,它无法控制它是如何生成的。我希望通过将它解组为由我手工编写的类来创建一个对象。
I have an XML which is out of my control on how it is generated. I want to create an object out of it by unmarshaling it to a class written by hand by me.
其结构的一个片段如下所示:
One snippet of its structure looks like:
<categories>
<key_0>aaa</key_0>
<key_1>bbb</key_1>
<key_2>ccc</key_2>
</categories>
我该如何处理此类案件?当然,元素数是可变的。
How can I handle such cases? Of course the element count of is variable.
推荐答案
如果使用以下对象模型,则每个未映射的key_#元素将保存为org.w3c.dom.Element的实例:
If you use the following object model then each of the unmapped key_# elements will be kept as an instance of org.w3c.dom.Element:
import java.util.List;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.w3c.dom.Element;
@XmlRootElement
public class Categories {
private List<Element> keys;
@XmlAnyElement
public List<Element> getKeys() {
return keys;
}
public void setKeys(List<Element> keys) {
this.keys = keys;
}
}
如果任何元素对应于使用@XmlRootElement注释映射的类,然后可以使用@XmlAnyElement(lax = true)并将已知元素转换为相应的对象。有关示例,请参阅:
If any of the elements correspond to classes mapped with an @XmlRootElement annotation, then you can use @XmlAnyElement(lax=true) and the known elements will be converted to the corresponding objects. For an example see:
- http://bdoughan.blogspot.com/2010/08/using-xmlanyelement-to-build-generic.html
这篇关于具有“未知”的JAXB映射元素名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!