serialize graph of javabeans into xml having separate xml file for each java instance -
could please suggest framework or tool serialize graph of javabeans xml having separate xml file each java instance? java xml tools managed find serialzie single file, need them separate, example:
model:
class { b b; } class b { } a = new a(); a.b = new b();
serialize :
a.xml:
<a> <property name="b>somehow ref b</property> </a>
b.xml
<b> </b>
best regards, ebu.
you use jaxb , xmladapter following:
a
import java.util.arraylist; import java.util.list; import javax.xml.bind.annotation.xmlrootelement; import javax.xml.bind.annotation.adapters.xmljavatypeadapter; @xmlrootelement @xmljavatypeadapter(myadapter.class) public class { private b b; private list<c> c; public a() { c = new arraylist<c>(); } public b getb() { return b; } public void setb(b b) { this.b = b; } public list<c> getc() { return c; } public void setc(list<c> c) { this.c = c; } }
b
import javax.xml.bind.annotation.xmlrootelement; import javax.xml.bind.annotation.adapters.xmljavatypeadapter; @xmlrootelement @xmljavatypeadapter(myadapter.class) public class b { }
c
import javax.xml.bind.annotation.xmlrootelement; import javax.xml.bind.annotation.adapters.xmljavatypeadapter; @xmlrootelement @xmljavatypeadapter(myadapter.class) public class c { }
myadapter
import java.io.file; import javax.xml.bind.jaxbcontext; import javax.xml.bind.jaxbexception; import javax.xml.bind.marshaller; import javax.xml.bind.annotation.adapters.xmladapter; public class myadapter extends xmladapter<string, object> { private static int counter = 1; private static jaxbcontext jaxbcontext; static { try { jaxbcontext = jaxbcontext.newinstance(a.class, b.class, c.class); } catch(jaxbexception e) { throw new runtimeexception(e); } } @override public object unmarshal(string v) throws exception { file xml = new file(v); return jaxbcontext.createunmarshaller().unmarshal(xml); } @override public string marshal(object v) throws exception { string filename = counter++ + ".xml"; file xml = new file(filename); marshaller marshaller = jaxbcontext.createmarshaller(); marshaller.setproperty(marshaller.jaxb_formatted_output, true); marshaller.marshal(v, xml); return filename; } }
demo
import javax.xml.bind.jaxbcontext; import javax.xml.bind.marshaller; public class demo { public static void main(string[] args) throws exception { jaxbcontext jc = jaxbcontext.newinstance(a.class, b.class, c.class); a = new a(); a.setb(new b()); a.getc().add(new c()); a.getc().add(new c()); marshaller marshaller = jc.createmarshaller(); marshaller.setproperty(marshaller.jaxb_formatted_output, true); marshaller.marshal(a, system.out); } }
Comments
Post a Comment