Unmarshalling nested list of xml items using JAXB(使用 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;
}
我想在解组后获取它们的列表.所有列表元素的类型、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 – 自定义编组和解组
这篇关于使用 JAXB 解组嵌套的 xml 项列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 JAXB 解组嵌套的 xml 项列表


基础教程推荐
- 从 python 访问 JVM 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01