使用 JAXB 解组嵌套的 xml 项目列表 [英] Unmarshalling nested list of xml items using JAXB

查看:42
本文介绍了使用 JAXB 解组嵌套的 xml 项目列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的 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; 
}

我想在解组后获得它们的列表.所有列表元素的类型、属性 1 和属性 2 值应该相同.有没有可能使用 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 – 自定义编组和解组

这篇关于使用 JAXB 解组嵌套的 xml 项目列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆