jaxb - annotating the addition of an attribute to an element -
i'm upgrading java object has xml representation in spirit:
<myobjects> <myobject uid="42" type="someenum"> <name>waldo</name> <description>yada yada</description> <myelement>some_string</myelement> ... </myobject> ... </myobjects>
myelement optional - can null in java / omitted in xml.
i'm adding field only relevant if myelement has actual value (and keep compatibility previous xml, it's optional in itself)
i'm trying avoid this:
<myelement>some_string</myelement> <myattr>foo</myattr>
and prefer this:
<myelement myattr="foo">some_string</myelement>
but banging head 2 days on how annotate it.
- i thought of marking xmltransient , let xmlanyelement catch instead while unmarshalling - seems cause problem when marshalling object java xml.
- i tried creating xmladapter element - unmarshal method gets inner content ("some_string"). am missing technique?
- is there way to element string ("<myelement myattr=\"foo\">some_string</myelement>") , process myself?
- do recommend other approach?
you can use eclipselink jaxb (moxy) @xmlpath extension accomplish this:
import javax.xml.bind.annotation.xmlaccesstype; import javax.xml.bind.annotation.xmlaccessortype; import javax.xml.bind.annotation.xmlattribute; import javax.xml.bind.annotation.xmlrootelement; import org.eclipse.persistence.oxm.annotations.xmlpath; @xmlrootelement @xmlaccessortype(xmlaccesstype.field) public class myobject { @xmlattribute private int uid; @xmlattribute private string type; private string name; private string description; private string myelement; @xmlpath("myelement/@myattr") private string myattr; }
this class interact following xml:
<myobject uid="42" type="someenum"> <name>waldo</name> <description>yada yada</description> <myelement myattr="foo">some_string</myelement> </myobject>
using following demo code:
import java.io.file; import javax.xml.bind.jaxbcontext; import javax.xml.bind.marshaller; import javax.xml.bind.unmarshaller; public class demo { public static void main(string[] args) throws exception { jaxbcontext jc = jaxbcontext.newinstance(myobject.class); file file = new file("input.xml"); unmarshaller unmarshaller = jc.createunmarshaller(); myobject myobject = (myobject) unmarshaller.unmarshal(file); marshaller marshaller = jc.createmarshaller(); marshaller.setproperty(marshaller.jaxb_formatted_output, true); marshaller.marshal(myobject, system.out); } }
to specify moxy jaxb implementation need include file called jaxb.properties in same package model classes following entry:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.jaxbcontextfactory
for more information on moxy's xpath based mapping see:
Comments
Post a Comment