Java JAXB-xsi:type封送
我对使用jaxb进行编组有点陌生,我正在尝试从我的对象生成此xml:Java JAXB-xsi:type封送,java,xml,jaxb,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> .... </Res
<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>
我必须创建一个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;
...
我已通过更改以下语句对其进行了修复:
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, TypeProcesBerichtResultBase.class)
注意我现在是如何将基类作为类型而不是实际的类进行编组的。这会显示xsi:type标记。如果您碰巧使用MOXy作为JAXB提供程序,那么您可能会幸运地获得这些信息。虽然这是另一种方式;这里使用xsi:type来反映Java继承,但也许您可以利用这种机制。@HeinBlöd我没有将MOXyWorks与JAXB
marshaller.marshall(…)
一起使用!
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)