问题
After this similar question yesterday I have another question concerning inheritance in XML schema and XJC bindings.
Given the following choice element such that Book and Journal have a common parent type (Publication
).
<xsd:choice >
<xsd:element name="Book" type="Book" />
<xsd:element name="Journal" type="Journal" />
</xsd:choice>
The Java class properties which are generated are like:
private Book book;
private Journal journal;
Since <xsd:choice>
means that there might be either a Book
or a Journal
I would prefer
private Publication bookOrJournal;
If I had a list of Publications by setting maxOccurs="unbounded"
in the choice element, it would work that way and I would get
private List<Publication> bookOrJournal;
How to achieve this with a non-collection property?
回答1:
You can using the following XJC binding to achieve this.
<xs:complexType name="myClass">
<xs:sequence>
<xs:choice>
<xs:annotation>
<xs:appinfo>
<jaxb:property name="bookOrJournal"/>
</xs:appinfo>
</xs:annotation>
<xs:element name="Book" type="Book"/>
<xs:element name="Journal" type="Journal"/>
</xs:choice>
</xs:sequence>
</xs:complexType>
After executing xjc <XSD File> -extension
, this generated the following Java class for me.
@XmlElements({
@XmlElement(name = "Book", type = Book.class),
@XmlElement(name = "Journal", type = Journal.class)
})
protected Publication bookOrJournal;
To use the XJC binding, I added the following to the top of my XSD.
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
jaxb:version="1.0" jaxb:extensionBindingPrefixes="xjc">
来源:https://stackoverflow.com/questions/10137968/xjc-java-class-generation-for-xschoice-element-which-is-not-unbounded