我正在使用 JAXB 为我正在编写的应用程序将 XML 绑定到 Java。我有一个名为measure的元素,它包含两个名为amount和maxAmount的数量元素,我想用它来模拟一个下限值和一个上限值。amount和maxAmount在其他方面是相同的,我希望它们在解组为 Java 时使用相同的类来实现。
以下是我提供给 JAXB 的 XML 模式的摘录:
<xsd:attributeGroup name="AmountAttributes">
<xsd:attribute name="quantity" type="xsd:decimal"/>
<xsd:attribute name="numerator" type="xsd:nonNegativeInteger"/>
<xsd:attribute name="denominator" type="xsd:positiveInteger"/>
</xsd:attributeGroup>
<xsd:element name="measure">
<xsd:complexType>
<xsd:sequence>
<xsd:element minOccurs="0" name="amount">
<xsd:complexType>
<xsd:attributeGroup ref="mpr:AmountAttributes"/>
</xsd:complexType>
</xsd:element>
<xsd:element minOccurs="0" name="maxAmount">
<xsd:complexType>
<xsd:attributeGroup ref="mpr:AmountAttributes"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
JAXB 从中创建了以下更详细的版本:
public class Measure {
protected Measure.Amount amount;
protected Measure.MaxAmount maxAmount;
public static class Measure.Amount {}
public static class Measure.MaxAmount {}
}
Measure.Amount和Measure.MaxAmount除了名称之外是相同的,但是——当然——就 Java 而言,它们彼此之间几乎没有关系。
有没有办法让 JAXB 对amount和maxAmount使用相同的类?
只是为了完全干净;-) 我应该提到我使用 Trang 从 RNC 生成 XML 模式。如果问题的答案是“更改 XML 模式”,我有补充问题“如何更改 RNC 以生成该 XML 模式?”。我的 RNC 看起来像这样:
AmountAttributes =
QuantityAttribute?
& attribute numerator { xsd:nonNegativeInteger }?
& attribute denominator { xsd:positiveInteger }?
QuantityAttribute = attribute quantity { xsd:decimal }
Measure =
element measure {
element amount { AmountAttributes }?,
element maxAmount { AmountAttributes }?
}+
我使用 RNC 是因为我发现它更易于理解,但如果我的问题的解决方案仅意味着使用 XML Schema,那就这样吧。
史蒂夫