2016-05-27 4 views
2

JAX-B(v.2.2.12)を使用してJavaオブジェクトツリーをマーシャリングしています。 整列化するクラスの一つはCaseObjectです:JAX-B:XMLAttributeから要素名を動的に生成

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

マーシャリング後の現在のXML represention:

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

必要なターゲットXML represention:

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

私の周りにプレイしました次のスニペット(example from a blog)を使用して@XmlAdapterを拡張してください:

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

質問:マーシャリング中にプロパティ(XMLAttribute)から要素名を動的に生成するためにJAX-Bを計測する方法はありますか?

答えて

1

次のXMLAdapter は私にとってはです。単に値タイプとしてJAXBElementを選択してください。 (あなたの具体的なオブジェクトは Boundタイプです。)このソリューションの前提条件は、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; 
} 

... 
+0

使用XMLAdaptersは完全を期すために言及されるべき潜在的な欠点:クラスが存在XMLAdaptersで注釈beeingてからXSDを生成する際に、現在自動的にXSDに変更に似するオプションはありません。 –

関連する問題