JAXB - 使用xsi:type进行编组

时间:2015-05-28 15:22:50

标签: java xml jaxb

我对使用jaxb进行编组是个新手,我试图从我的对象中创建这个xml:

<Process_Bericht_Result xsi:type="Type_Proces_Bericht_Result_v2"
xmlns="http://www.centralbrokersystem.org"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
   <Result_Data>
      ....
   </Result_Data>
</Process_Bericht_Result>

我得到的是以下内容:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Proces_Bericht_result xmlns="http://www.centralbrokersystem.org">
    <Result_Data>
       ...
    </Result_Data>
</Proces_Bericht_result>

我想定义xsi:type ...

我使用以下代码创建这些对象:

JAXBElement element = new JAXBElement(
            new QName("http://www.centralbrokersystem.org", "Proces_Bericht_Result"), TypeProcesBerichtResultV2.class, typeProcesBerichtResultV2);

我必须创建一个JAXBElement,因为TypeProcesBerichtResultV2类没有用@RootElement注释,而且它是用jaxB maven插件生成的,所以我无法改变它。

然后我调用了一个方法:

XmlUtils.object2Xml(element, TypeProcesBerichtResultV2.class)

并且该方法的实现是:

    public static String object2Xml(Object obj,
                                Class clazz)  {
    String marshalledObject = "";
    if (obj != null) {
        try {
            JAXBContext jc = JAXBContext.newInstance(clazz);
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                    new Boolean(true));
            StringWriter sw = new StringWriter();

            marshaller.marshal(obj, sw);
            marshalledObject = new String(sw.getBuffer());
        } catch (Exception ex) {
            throw new RuntimeException("Unable to marshall the object", ex);
        }
    }
    return marshalledObject;
}

我应该更改为正确的xml编组?

我试图编组的元素是以下生成的对象:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Type_Proces_Bericht_Result_v2", propOrder = {
"resultData",
"statusPartner"
})
public class TypeProcesBerichtResultV2
    extends TypeProcesBerichtResultBase
{

    @XmlElement(name = "Result_Data", required = true)
    protected TypeResultData resultData;

    ...

1 个答案:

答案 0 :(得分:2)

我通过更改以下声明来修复它:

 JAXBElement element = new JAXBElement(
        new QName("http://www.centralbrokersystem.org", "Proces_Bericht_Result"), TypeProcesBerichtResultV2.class, typeProcesBerichtResultV2);

更改为:

JAXBElement element = new JAXBElement(
        new QName("http://www.centralbrokersystem.org", "Proces_Bericht_Result"), TypeProcesBerichtResultBase.class, typeProcesBerichtResultV2);

XmlUtils.object2Xml(element, TypeProcesBerichtResultV2.class)

更改为

XmlUtils.object2Xml(element, TypeProcesBerichtResultBase.class)

注意我现在如何使用baseClass作为类型而不是实际的类进行编组。这会广告xsi:type标记。