具有“未知"的 JAXB 映射元素名称

2022-01-19 00:00:00 xml java jaxb unmarshalling

我有一个无法控制生成方式的 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

相关文章