【问题标题】:JAXB xsi:type subclass unmarshalling not workingJAXB xsi:类型子类解组不起作用
【发布时间】:2023-03-14 20:02:01
【问题描述】:

我正在按照这篇经常被引用的博客文章中有关使用 xsi:type 的说明进行操作:

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。都不行。

这不应该工作还是我错过了一些设置?

【问题讨论】:

    标签: java jaxb


    【解决方案1】:

    在您的测试用例中,您需要指定DocumentBuilderFactory 是命名空间感知的。如果没有此设置,您的 JAXB 实现的 DOM 输入将不会包含格式正确的 xsi:type 属性。

        documentBuilderFactory.setNamespaceAware(true);
    

    【讨论】:

    • 工作,谢谢!为什么这不是默认值?
    猜你喜欢
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 2014-12-25
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多