2012-06-27 87 views
4

我下面就使用XSI的指令:從這個經常被引用的博客文章類型:JAXB XSI:類型子解組無法正常工作

http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-xsitype.html

基本上我有這樣的:

public abstract class ContactInfo { 
} 

public class Address extends ContactInfo { 

    private String street; 

    public String getStreet() { 
     return street; 
    } 

    public void setStreet(String street) { 
     this.street = street; 
    } 
} 

@XmlRootElement 
public class Customer { 

    private ContactInfo contactInfo; 

    public ContactInfo getContactInfo() { 
     return contactInfo; 
    } 

    public void setContactInfo(ContactInfo contactInfo) { 
     this.contactInfo = contactInfo; 
    } 
} 

而這個測試:

@Test 
public void contactTestCase() throws JAXBException, ParserConfigurationException, IOException, SAXException { 
    Customer customer = new Customer(); 
    Address address = new Address(); 
    address.setStreet("1 A Street"); 
    customer.setContactInfo(address); 

    JAXBContext jc = JAXBContext.newInstance(Customer.class, Address.class, PhoneNumber.class); 
    StringWriter writer = new StringWriter(); 
    Marshaller marshaller = jc.createMarshaller(); 
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
    marshaller.marshal(customer, writer); 
    String s = writer.toString(); 
    System.out.append(s); 

    StringInputStream sis = new StringInputStream(s); 
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder db = documentBuilderFactory.newDocumentBuilder(); 
    Document doc = db.parse(sis); 

    Unmarshaller um = jc.createUnmarshaller(); 
    JAXBElement result = um.unmarshal(doc, Customer.class); 
    Customer f = (Customer) result.getValue(); 

    writer = new StringWriter(); 
    marshaller.marshal(customer, writer); 
    s = writer.toString(); 
    System.out.append(s); 
} 

我得到這樣的結果:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<customer> 
    <contactInfo xsi:type="address" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
     <street>1 A Street</street> 
    </contactInfo> 
</customer> 

javax.xml.bind.UnmarshalException: Unable to create an instance of blog.inheritance.ContactInfo 

我試過JAXB,JAXB-IMPL-2.1.2的默認實現和基於關閉此bug,我已經試過JAXB-IMPL-2.2.6-b38.jar。它沒有任何作用。

這不應該工作,或者我錯過了一些設置?

回答

5

在您的測試案例中,您需要指定DocumentBuilderFactory是可識別名稱空間的。如果沒有此設置,那麼JAXB實現的DOM輸入將不包含正確形成的xsi:type屬性。

documentBuilderFactory.setNamespaceAware(true); 
+2

Doh!現在工作。謝謝! – jamie

+0

工作過,謝謝!爲什麼這不是默認? –