我正在使用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)动态生成元素名称?

最佳答案

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

...

10-07 12:09