JAX-B:从XMLAttribute动态生成元素名称

时间:2016-05-27 14:39:40

标签: java xml jaxb

我正在使用JAX-B(v.2.2.12)编组java对象树。 要编组的一个类是CaseObject:

public class CaseObject {
...
  @XmlAnyElement
  @XmlJavaTypeAdapter(ParameterAdapter.class)
  protected List <CaseObject> caseObjects;
...
}

编组后的当前xml表示:

<caseObject id="1" name="someName" typeId="0">
         ...
        <caseObject id="29" key="someOtherName" typeId="12">
         ...
        </caseObject>
</caseObject>

所需的目标xml代表:

<someName id="1" name="someName" typeId="0">
         ...
        <someOtherNameid="29" key="someOtherName" typeId="12">
         ...
        </someOtherName>
</someName>

我使用以下代码段(@XmlAdapter)扩展example from a blog,我已经玩过了:

    @Override
    public Element marshal(CaseObject caseObject) throws Exception {
    if (null == caseObject) {
        return null;
    }

    // 1. Build a JAXBElement
    QName rootElement = new QName(caseObject.getName());
    Object value = caseObject;
    Class<?> type = value.getClass();
    JAXBElement jaxbElement = new JAXBElement(rootElement, type, value);

    // 2.  Marshal the JAXBElement to a DOM element.
    Document document = getDocumentBuilder().newDocument();
    Marshaller marshaller = getJAXBContext(type).createMarshaller();

    // where the snake bites its own tail ...
    marshaller.marshal(jaxbElement, document);
    Element element = document.getDocumentElement();

    return element;
}

问题是:如何检测JAX-B在编组期间从属性(XMLAttribute)动态生成元素名称?

1 个答案:

答案 0 :(得分:1)

以下XMLAdapter 适用于我。只需选择JAXBElement作为适配器 ValueType 即可。 (当然,使用具体对象作为 BoundType 。)此解决方案的前提条件是,QName的值是有效的xml元素名称。

public class CaseObjectAdapter extends XmlAdapter<JAXBElement, CaseObject> {

@Override
public JAXBElement marshal(CaseObject caseObject) throws Exception {

    JAXBElement<CaseObject> jaxbElement = new JAXBElement(new QName(caseObject.methodThatReturnsAnElementName()), caseObject.getClass(), caseObject);

    return jaxbElement;
}

...