天天看點

JAXB如何Marshal父類?

<link rel="stylesheet" type="text/css" href="http://maomaode.bokeland.com/plugins/plogeshi/styles/plogeshi.css" target="_blank" rel="external nofollow" >假設我們有這樣的Schema:

<complexType name="Meta">
       <sequence>                
          <element name="name" type="string"/"">
           <element name="description" type="string"/"">
       </sequence>
   </complexType>
 
   <complexType name="Store">
       <complexContent>
           <extension base="Meta">
               <sequence>
                   <element name="books" type="Book" maxoccurs="unbounded"/"">
               </sequence>
           </extension>
       </complexContent>
   </complexType>
 
   <element name="store" type="Store"/"">
   <element name="meta" type="Meta"/""> 
       

注意到Store 繼承了Meta, 如果我們有一個Store的對象,但是我們隻想Marshal出繼承Meta部分的内容,即希望得到下面這樣XML

<meta>
<name>my book store </name>
<description> abc </description>
</meta> 
       

應該怎麼寫呢?答案其實就在于你怎麼建構JAXBContext

JAXBElement jaxbElement = 
    (JAXBElement)m.invoke(objFactory.newInstance(), store);
 
JAXBContext jc = JAXBContext.newInstance(Meta.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(jaxbElement, os);