我对 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>
Run Code Online (Sandbox Code Playgroud)
我得到的是以下内容:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Proces_Bericht_result xmlns="http://www.centralbrokersystem.org">
<Result_Data>
...
</Result_Data>
</Proces_Bericht_result>
Run Code Online (Sandbox Code Playgroud)
我想定义 xsi:type...
我使用以下代码创建这些对象:
JAXBElement element = new JAXBElement(
new QName("http://www.centralbrokersystem.org", "Proces_Bericht_Result"), TypeProcesBerichtResultV2.class, typeProcesBerichtResultV2);
Run Code Online (Sandbox Code Playgroud)
我必须创建一个 JAXBElement,因为 TypeProcesBerichtResultV2 类未使用 @RootElement 进行注释,并且它是使用 jaxB maven 插件生成的,因此我无法更改它。
然后我调用一个方法:
XmlUtils.object2Xml(element, TypeProcesBerichtResultV2.class)
Run Code Online (Sandbox Code Playgroud)
该方法的实现是:
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;
}
Run Code Online (Sandbox Code Playgroud)
我应该更改什么才能编组到正确的 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;
...
Run Code Online (Sandbox Code Playgroud)
我通过更改以下语句来修复它:
JAXBElement element = new JAXBElement(
new QName("http://www.centralbrokersystem.org", "Proces_Bericht_Result"), TypeProcesBerichtResultV2.class, typeProcesBerichtResultV2);
Run Code Online (Sandbox Code Playgroud)
变成:
JAXBElement element = new JAXBElement(
new QName("http://www.centralbrokersystem.org", "Proces_Bericht_Result"), TypeProcesBerichtResultBase.class, typeProcesBerichtResultV2);
Run Code Online (Sandbox Code Playgroud)
和
XmlUtils.object2Xml(element, TypeProcesBerichtResultV2.class)
Run Code Online (Sandbox Code Playgroud)
变成
XmlUtils.object2Xml(element, TypeProcesBerichtResultBase.class)
Run Code Online (Sandbox Code Playgroud)
请注意我现在如何使用 baseClass 作为类型而不是实际的类进行编组。这会广告 xsi:type 标记。
| 归档时间: |
|
| 查看次数: |
5496 次 |
| 最近记录: |