2011-02-03 76 views
6

我有JAXB生成的類的層次結構。我想編組一個子類作爲一個基類元素(但所有的子類屬性),使用xsi:type來指示具體的類型。JAXB編組和多態性

例如,給予動物和鳥亞綱:

<xs:complexType name="animal" abstract="true"> 
    <xs:sequence> 
     <xs:element name="name" type="xs:string"/> 
    </xs:sequence> 
</xs:complexType> 

<xs:complexType name="bird"> 
    <xs:complexContent> 
     <xs:extension base="animal"> 
      <xs:sequence> 
       <xs:element name="maxAltitude" type="xs:int"/> 
      </xs:sequence> 
     </xs:extension> 
    </xs:complexContent> 
</xs:complexType> 

<xs:element name="Animal" type="animal"/> 
<xs:element name="Bird" type="bird"/> 

不管我怎麼元帥鳥,例如:

Bird sparrow = new Bird(); 
sparrow.setName("Sparrow"); 
sparrow.setMaxAltitude(1000); 

JAXBContext context = JAXBContext.newInstance(Animal.class, Bird.class); 
Marshaller marshaller = context.createMarshaller(); 
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
marshaller.marshal(sparrow, System.out); 

結果始終是一個鳥的元素:

<Bird xmlns="http://mycompany.com/animals"> 
    <name>Sparrow</name> 
    <maxAltitude>1000</maxAltitude> 
</Bird> 

但是我想要的是這個(子類的所有屬性,xsi類型,基類元素名稱):

<Animal xmlns="http://mycompany.com/animals" 
     xsi:type="bird" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <name>Sparrow</name> 
    <maxAltitude>1000</maxAltitude> 
</Animal> 

有什麼奇怪的是,如果我創建一個包裝元素:

<xs:complexType name="animalWrapper"> 
    <xs:sequence> 
     <xs:element name="Animal" type="animal"/> 
    </xs:sequence> 
</xs:complexType> 

<xs:element name="AnimalWrapper" type="animalWrapper"/> 

元帥,它使用了基類:

<AnimalWrapper xmlns="http://mycompany.com/animals" 
    <Animal xsi:type="bird" 
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
     <name>Sparrow</name> 
     <maxAltitude>1000</maxAltitude> 
    </Animal> 
</AnimalWrapper> 

如果我手動建立我需要的XML文檔,JAXB解組它沒有問題。我如何編寫我的XML模式和/或配置JAXB以允許我想要的編組行爲?

謝謝。

回答

1

你可以做到以下幾點:

QName qName = jc.createJAXBIntrospector().getElementName(new Animal()); 
JAXBElement<Animal> jaxbElement = new JAXBElement<Animal>(qName, Animal.class, new Bird()); 
marshaller.marshal(jaxbElement, System.out); 

退房:

+0

感謝。你的例子有一個包含多態的項目的包裝,就像我的AnimalWrapper示例一樣,而不是我正在尋找的東西。我想要根元素的多態性。 – SingleShot 2011-02-03 18:35:53