2015-05-28 50 views
0

我是一种新的与JAXB编组,我想从我的对象使这个XML:JAXB - 名帅与XSI:类型

<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:类型...

我创建用下面的代码中的对象:

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; 

    ... 
+0

如果你碰巧使用莫西为您的JAXB提供者,你可能有一些运气的信息[这里](http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-xsitype。 HTML)。虽然这是另一种方式; xsi:type在这里用来反映Java的继承,但也许你可以利用这种机制。 –

+0

@HeinBlöd我不使用莫西 – GregD

回答

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) 

注意如何我现在与基类编组类型,而不是实际的类。这个广告xsi:类型标签。