I’m upgrading a Java object that currently has XML representation in this spirit:
<myObjects>
<myObject uid="42" type="someEnum">
<name>Waldo</name>
<description>yada yada</description>
<myElement>some_string</myElement>
...
</myObject>
...
</myObjects>
myElement is optional – it can be null in Java / omitted in XML.
I’m adding a field that is only relevant if myElement has an actual value
(and to keep compatibility with previous XML, it’s optional in itself)
I’m trying to avoid this:
<myElement>some_string</myElement>
<myAttr>foo</myAttr>
and prefer something like this:
<myElement myAttr="foo">some_string</myElement>
but banging my head for 2 days now on how to annotate it.
- I thought of marking it with XmlTransient and let an XmlAnyElement catch it instead while unmarshalling – but it seems this will cause a problem when marshalling the object back from Java to XML.
- I tried creating an XmlAdapter for the element – but the unmarshal method gets only the inner content (“some_string”). Am I missing something with this technique?
- Is there a way to just get the element as a string (“<myElement myAttr=\”foo\”>some_string</myElement>”) and I will process it myself?
- Do you recommend any other approach?
You can use the EclipseLink JAXB (MOXy) @XmlPath extension to easily accomplish this:
This class will interact with the following XML:
Using the following demo code:
To specify MOXy as your JAXB implementation you need to include a file called jaxb.properties in the same package as your model classes with the following entry:
For more information on MOXy’s XPath based mapping see: