【问题标题】:JAXB - marshal with xsi:typeJAXB - 使用 xsi:type 编组
【发布时间】:2015-05-28 15:22:49
【问题描述】:

我对使用 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;

    ...

【问题讨论】:

  • 如果您碰巧使用 MOXy 作为您的 JAXB 提供程序,您可能会对here 的信息感到幸运。虽然有点相反; xsi:type 在这里用于反映 Java 继承,但也许您可以利用该机制。
  • @HeinBlöd 我没有使用 MOXy

标签: java xml jaxb


【解决方案1】:

我已通过更改以下语句来修复它:

 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 标签。

【讨论】:

  • 也适用于 JAXB marshaller.marshal(...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-21
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
相关资源
最近更新 更多