使用 JAXB 解组嵌套的 xml 项列表

2022-01-19 00:00:00 xml java jaxb2

我有这样的 xml 构造,我需要使用 JAXB 将其转换为 java 对象:

I've got such xml construction which I need to convert into java objects using JAXB:

<elements>
    <elemet>
        <type></type>
        <property1></property1>
        <property2></property2>
        <items>
            <item>
                <id></id>
                <name></name>
            </item>
            ...
            <item>
                <id></id>
                <name></name>
            </item>
        </items>
    </element>
</elements>

我不应该将此构造转换为具有嵌套项目列表的元素,而是转换为每个项目一个的多个元素.这是 Element 类的示例:

I should convert this construction not into element with nested list of items but into several elements one for every item. Here is example of Element class:

class Element {
    Integer type;
    String property1;
    String property2;
    Integer itemId;
    String itemName; 
}

我想在解组后获取它们的列表.所有列表元素的类型、property1 和 property2 值应该相同.有没有可能使用 JAXB 解决这个问题?

I want to get list of them after unmarshalling. Type, property1 and property2 values should be the same for all list elements. Is there any possibility to solve this problem using JAXB?

推荐答案

您需要定义一个自定义 XmlAdapter.在您的案例中,复杂的部分是您希望将一个 XML element 映射到多个 Java Element 对象.这意味着,在 Java 中,您的 XmlAdapter 需要配置为收集 Element 对象.假设您的示例 XML 片段是文档的一部分:

You will need to define a custom XmlAdapter. The complicated part in your case is that you want to map one XML element into multiple Java Element objects. This means that, in Java., your XmlAdapter needs to be configured for collection of Element objects. Assuming your example XML fragment is part of a document:

<document>
   <elements> 
      <element>
          ....
      </element>
   <elements>
</document>    

然后你需要为Java Document类中的List字段配置XmlAdapter:

Then you will need to configure the XmlAdapter for the List<Element> field in the Java Document class:

class Document {
     @XmlJavaTypeAdapter(CustomAdapter.class)
     List<Element> elements;
}

然后您的 CustomAdapter 类可以接收 Element 对象列表(对应于具有嵌套项的实际 XML 结构)并生成具有所需结构的 Element 列表.

Then you your CustomAdapter class can receive a list of Element objects (corresponding to the actual XML structure with the nested items) and produce a list of Element with the structure you want.

例如,查看 JAXB XmlAdapter – 自定义编组和解组

相关文章