我有以下 XSD
来自供应商的片段,我无法更改它的指定方式:
<xsd:element name="navmap">
<xsd:complexType>
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element ref="navitem"/>
<xsd:element ref="debug"/>
</xsd:choice>
<xsd:attribute name="focus" type="xsd:string" use="optional"/>
</xsd:complexType>
</xsd:element>
现在没有自定义,它会生成以下代码
@XmlElements({
@XmlElement(name = "navitem", type = Navitem.class),
@XmlElement(name = "debug", type = Debug.class)
})
protected List<Object> navitemOrDebug;
我宁愿它为每种类型生成一个单独的列表,如下所示
@XmlElements({
@XmlElement(name = "navitem", type = Navitem.class)
})
protected List<Navitem> navitems;
@XmlElements({
@XmlElement(name = "debug", type = Debug.class)
})
protected List<Debug> debugs;
我的 .xjb
中有以下内容重命名整个 List
的文件但我不知道如何拆分它们。
<jxb:bindings node="//xsd:element[@name='navmap']//xsd:complexType//xsd:choice">
<jxb:property name="contents" />
</jxb:bindings>
如何指定我想要一个单独的 List
或 Set
对于外部 .xjb
中的每种类型绑定(bind)文件?
如果我做不到,我该如何添加 <jaxb:annotation/>
到 .xsd
文件以指定一个单独的 List
或 Set
对于每种类型?
我不关心顺序,在这种特殊情况下顺序并不重要。
注意: 我更喜欢外部 .xjb
解决方案,我不想将自定义 .xsd 与供应商提供的每个新版本进行比较,它们太多了。
最佳答案
如约而至,请见Simplify Plugin .
这个插件可以简化“复杂”的属性。这些属性通常是从像这样的可重复选择中生成的:
<xs:complexType name="typeWithReferencesProperty">
<xs:choice maxOccurs="unbounded">
<xs:element name="a" type="someType"/>
<xs:element name="b" type="someType"/>
</xs:choice>
</xs:complexType>
...
<xs:complexType name="typeWithElementsProperty">
<xs:choice maxOccurs="unbounded">
<xs:element name="a" type="xs:string"/>
<xs:element name="b" type="xs:int"/>
</xs:choice>
</xs:complexType>
默认情况下,XJC 会将复杂属性建模为多个引用或元素。
@XmlElementRefs({
@XmlElementRef(name = "a", type = JAXBElement.class),
@XmlElementRef(name = "b", type = JAXBElement.class)
})
protected List<JAXBElement<SomeType>> aOrB;
...
@XmlElements({
@XmlElement(name = "a", type = String.class)
@XmlElement(name = "b", type = Integer.class),
})
protected List<Serializable> aOrB;
需要这些复杂的属性来充分模拟 XML 模式的复杂内容,即在可重复选择中保持元素的顺序。 不幸的是,它们不是惯用的 bean 属性。这些属性是“异构的”(从某种意义上说,它们存储不同的类型),这使得使用它们变得困难。
然而,如果元素的顺序不重要——也就是说,你可以接受它在重新编码后会改变的事实,这些属性的结构可以简化:复杂的属性可以拆分成几个简单的属性。
Simplify 插件实现了这个任务。它允许您简化复杂的属性。该插件将删除复杂属性并插入几个更简单的属性而不是原始(复杂)属性。所以你可以得到类似的东西:
@XmlElement(name = "a", type = String.class)
protected List<String> a;
@XmlElement(name = "b", type = Integer.class)
protected List<Integer> b;
或者:
@XmlElement(name = "a")
protected List<SomeType> a;
@XmlElement(name = "b")
protected List<SomeType> b;
或者:
@XmlElementRef(name = "a", type = JAXBElement.class)
protected List<JAXBElement<SomeType>> a;
@XmlElementRef(name = "b", type = JAXBElement.class)
protected List<JAXBElement<SomeType>> b;
取决于定制。
插件将于JAXB2 Basics发布0.6.3,现在可作为 this repository 的快照使用.
关于java - 我如何分离 <xsd :choice/> sub-elements into individual Collection properties using JAXB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7033600/