/ / JAXB - marszałek z xsi: type - java, xml, jaxb

JAXB - marszałek z xsi: type - java, xml, jaxb

Jestem trochę nowy w marshalling z jaxb i próbuję utworzyć ten xml z moich obiektów:

<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>

Dostaję następujące:

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

Chciałbym zdefiniować xsi: type ...

Tworzę te obiekty za pomocą następującego kodu:

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

Muszę utworzyć JAXBElement, ponieważ klasa TypeProcesBerichtResultV2 nie jest opatrzona adnotacją @RootElement i jest generowana za pomocą wtyczki jaxB maven, więc nie mogę jej zmienić.

Następnie wywołuję metodę:

XmlUtils.object2Xml(element, TypeProcesBerichtResultV2.class)

a implementacja tej metody jest:

    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;
}

Co powinienem zmienić na marszałka na prawidłowy xml?

Element, który próbuję sprowadzić, to wygenerowany obiekt:

@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;

...

Odpowiedzi:

2 dla odpowiedzi № 1

Naprawiłem to przez zmianę następujących instrukcji:

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

zmienić na:

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

i

XmlUtils.object2Xml(element, TypeProcesBerichtResultV2.class)

zmienić na

XmlUtils.object2Xml(element, TypeProcesBerichtResultBase.class)

Zauważ, że teraz zbieram z klasą baseClass jako typ zamiast rzeczywistej klasy. To powoduje wyświetlenie znacznika xsi: type.