带有“未知"的 JAXB 映射元素姓名 [英] JAXB mapping elements with "unknown" name
问题描述
我有一个 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:
这篇关于带有“未知"的 JAXB 映射元素姓名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!