java - How to create object graph from an XML-file? -


i have xml file. like:

<person>   <name>     <firstname>joni</firstname>     <lastname>smith</lastname>   </name>   <born year="1983" day="31" month="01">finland</born>   ... lots of elements ... </person> 

my goal create class person. how can "automatically"? think have used maven castor plugin create quite complicated object graph xml file without lot of effort. however, can not remember plugin was, , indeed can not remember how did used it. happy learn other (probably better) tools might know.

i agree using jaxb.

starting xml schema (generate classes xml schema)

you can use jaxb generate java source code xml schema. below instructions doing eclipselink jaxb (moxy):

java se 6 comes metro jaxb xjc compiler can found in bin directory of jdk installation:

c:\program files\java\jdk1.6.0_20\bin>xjc -d outputdir myschema.xsd 

the dali plug-in in eclipse has support see section on jaxb class generation:

starting objects

with object model may find xpath based mapping extension in moxy jaxb useful:

import javax.xml.bind.annotation.xmlaccesstype; import javax.xml.bind.annotation.xmlaccessortype; import javax.xml.bind.annotation.xmlrootelement;  import org.eclipse.persistence.oxm.annotations.xmlpath;  @xmlrootelement @xmlaccessortype(xmlaccesstype.field) public class person {      @xmlpath("name/firstname/text()")     private string firstname;      @xmlpath("name/lastname/text()")     private string lastname;      // ... } 

can used following demo code work xml:

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(person.class);          unmarshaller unmarshaller = jc.createunmarshaller();         person person = (person) unmarshaller.unmarshal(new file("input.xml"));          marshaller marshaller = jc.createmarshaller();         marshaller.setproperty(marshaller.jaxb_formatted_output, true);         marshaller.marshal(person, system.out);     } } 

for more information on xpath based mappings see:

for "born" element might find jaxb's xmladapter helpful:


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -