本文介绍了JAX-B:从XMLAttribute动态生成元素名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JAX-B(v.2.2.12)封送Java对象树.要编组的类之一是CaseObject:

I'm using JAX-B (v.2.2.12) to marshal a java objects tree.One of the classes to be marshalled is CaseObject:

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

编组后的当前xml表示形式:

The current xml represention after marshalling:

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

所需的目标xml表示形式:

The required target xml represention:

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

我通过扩展 @XmlAdapter 使用以下代码段(博客中的示例):

I've played around by extending @XmlAdapter using the following snippet (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)动态生成元素名称?

Question is: How to instrument JAX-B to dynamically generate Element names from a property(XMLAttribute) during marshalling?

推荐答案

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

The following XMLAdapter works for me. Simply choose JAXBElement as the adapters ValueType. (use your concrete object as BoundType, of course.) This solution's precondition is, that the QName's value is a valid xml element name.

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

...

这篇关于JAX-B:从XMLAttribute动态生成元素名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 15:57