2012-12-04 110 views
2

我遇到了使用jaxb2-maven-plugin(1.5)解組XML的問題。基本上,在我的XML文檔中,有一個B類型的元素A,它是基類域類A類。類型B是一個擴展爲A的域類。現在,我可以看到XML以元素A與xsi :類型= 「B」。但是當我解組時,它仍然返回一個類型爲A的Java對象。我該如何解決這個問題?我需要能夠獲得類型B的對象。只要XML具有符號xsi:type,它應該能夠解組它,正確。或者我還需要XMLAdapters等?JAXB解組問題

非常感謝。

回答

2

有幾件事情要檢查:

  • 是您JAXBContext意識到B類的?您可以包括在用於創建JAXBContext的類中,或者在A類中添加@XmlSeeAlso({B.class})
  • 是與BB對應的類型的名稱?默認爲b。您可以使用@XmlType註釋來指定名稱。

package forum13712986; 

import javax.xml.bind.annotation.XmlSeeAlso; 

@XmlSeeAlso({B.class}) 
public class A { 

} 

package forum13712986; 

import javax.xml.bind.annotation.XmlType; 

@XmlType(name="B") // Default name is "b" 
public class B extends A { 

} 

演示

package forum13712986; 

import java.io.StringReader; 
import javax.xml.bind.*; 
import javax.xml.transform.stream.StreamSource; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     JAXBContext jc = JAXBContext.newInstance(A.class); 

     Unmarshaller unmarshaller = jc.createUnmarshaller(); 
     String xml = "<A xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:type='B'/>"; 
     StreamSource source = new StreamSource(new StringReader(xml)); 
     JAXBElement<A> jaxbElement = unmarshaller.unmarshal(source, A.class); 

     System.out.println(jaxbElement.getValue().getClass()); 
    } 

} 

輸出

class forum13712986.B