问题
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;
...
}
The current xml represention after marshalling:
<caseObject id="1" name="someName" typeId="0">
...
<caseObject id="29" key="someOtherName" typeId="12">
...
</caseObject>
</caseObject>
The required target xml represention:
<someName id="1" name="someName" typeId="0">
...
<someOtherNameid="29" key="someOtherName" typeId="12">
...
</someOtherName>
</someName>
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;
}
Question is: How to instrument JAX-B to dynamically generate Element names from a property(XMLAttribute) during marshalling?
回答1:
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;
}
...
来源:https://stackoverflow.com/questions/37486280/jax-b-dynamically-generate-element-name-from-xmlattribute