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 项列表


- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01