问题描述
我希望能够使用JAXB处理这种格式的XML ...
I would like to be able to process XML of this format using JAXB ...
<configuration>
<!-- more content here -->
<things>
<thing>
<name>xx1</name>
<value>yy1</value>
</thing>
<thing>
<name>xx2</name>
<value>yy2</value>
</thing>
</things>
<!-- more content here -->
</configuration>
我想把上面的XML编组到这些Java类中(为简单起见,我留下了修饰符等as public
, protected
以及getter / setters away):
I'd like to marshal the above XML into these Java classes (for simplicity, I left modifiers such as public
, protected
as well as getters/setters away):
class Configuration {
List<Thing> things;
}
class Thing {
String name;
String value;
}
我当前XSD结构的相关部分大致如下:
The relevant part of my current XSD structure roughly looks like this:
<complexType name="Configuration">
<sequence>
<!-- ... -->
<element name="things" type="ns:Things" minOccurs="0" maxOccurs="unbounded"/>
<!-- ... -->
</sequence>
</complexType>
<complexType name="Things">
<sequence>
<element name="thing" type="ns:Thing" minOccurs="0" maxOccurs="unbounded"/>
</sequence>
</complexType>
不幸的是,XJC还为生成类
即使在处理的Java部分中确实没有必要。所以我的输出是:
Unfortunately, XJC generates also a class for Things
even if that is really unnecessary in the Java part of the processing. So my output is this:
class Configuration {
Things things;
}
class Things {
List<Thing> thing;
}
class Thing {
String name;
String value;
}
我有什么方法可以告诉XJC避免产生这种不必要的类?或者有什么方法可以重新说出我的XSD以避免这一代?这两个选项都适合我。
Is there any way I can tell XJC to avoid generating this unnecessary class? Or is there any way I can re-phrase my XSD in order to avoid that generation? Both options would be fine with me.
事实上,我想我需要生成 @XmlElementWrapper
注释如下所示:
In fact, I guess I would need to generate the @XmlElementWrapper
annotation as documented here:
- Mapping Java collections which contains super- and sub-types with JAXB
- JAXB List Tag creating inner class
推荐答案
此问题中记录了一个可能的解决方案:
A possible solution is documented in this question here:
这允许生成以下Java代码,正是我所需要的(无关的注释省略):
This XJC plugin allows for generating the following Java code, doing precisely what I needed (irrelevant annotations omitted):
class Configuration {
@XmlElementWrapper(name = "things")
@XmlElement(name = "thing")
List<Thing> things;
}
class Thing {
String name;
String value;
}
这篇关于如何编写我的XSD以便使用JAXB和XJC匹配所需的XML和Java格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!