使用JAXB解组嵌套的xml项列表 [英] Unmarshalling nested list of xml items using JAXB
问题描述
我有这样的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;
}
我希望在解组之后得到它们的列表。对于所有列表元素,Type,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 元素
映射到多个Java 元素
对象。这意味着,在Java中,您的 XmlAdapter
需要配置为元素
对象的集合。假设您的示例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>
然后你需要配置 XmlAdapter
对于Java 文档
类中的列表<元素>
字段:
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
class可以接收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屋!