how to map same value to two different fields in jaxb while marshalling and unmarshalling -
i have xml tag hello there field below in java
class helloworld{ @xmlelement private string name; }
while unmarshalling assigns hello value name variable.now want create new xml java object(helloworld) doing marshalling in case want xml tag instead of in xml. how can acheive in jaxb?
both xml not in control cannot change tag name
edit:
incoming xml - helloworld.xml
<helloworld> <name>hello</name> </helloworld> @xmlrootelement(name="helloworld) class helloworld{ @xmlelement(name="name") private string name; // setter , getter name } jaxbcontext context = jaxbcontext.newinstance(helloworld.class); unmarshaller un = conext.createunmarshaller un(); helloworld hw = un.unmarshal(new file("helloworld.xml")); system.out.println(hw.getname()); // print hello <name> tag mapped name variable.
now want use hw object of helloworld object create xml below
<helloworld> <name_1>hello</name_1> // note <name> changed <name_1> </helloworld>
i not want create class helloworld , declare variable name_1 in new class .i want reuse helloworld class because tag name has been changed.
but use existing helloworld class , try marshal object hw below
jaxbcontext context = jaxbcontext.newinstance(helloworld.class); marshaller m = conext.createmarshaller(); stringwriter writer = new stringwriter(); m.marshal(hw,writer); system.out.println(writer.tostring());
this print below
<helloworld> <name>hello</name> </helloworld>
but require
<helloworld> <name_1>hello</name_1> // note <name> changed <name_1> </helloworld>
the reason incoming xml before unmarshalling , outgoing xml after marshalling not under control.
hope explains.
option #1 - works jaxb implementations
you use xslt transform transform jaxbsource
xml want:
// create transformer transformerfactory tf = transformerfactory.newinstance(); streamsource xslt = new streamsource( "src/blog/jaxbsource/xslt/stylesheet.xsl"); transformer transformer = tf.newtransformer(xslt); // source jaxbcontext jc = jaxbcontext.newinstance(library.class); jaxbsource source = new jaxbsource(jc, catalog); // result streamresult result = new streamresult(system.out); // transform transformer.transform(source, result);
for more information
option #2 - works eclipselink jaxb (moxy)
note: i'm moxy lead.
moxy provides mapping document extension can use override mappings @ field/property level. means create 1 jaxbcontext
on annotations, , second jaxbcontext
based on annotations xml overrride.
for more information
Comments
Post a Comment