users@jaxb.java.net

Re: How to unmarshal nested xml element to java object

From: Wolfgang Laun <wolfgang.laun_at_gmail.com>
Date: Wed, 4 Apr 2012 12:34:12 +0200

You use a smattering of annotations:

@XmlRootElement( name = "employee" )
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee{
    @XmlAttribute
    public String id;

    @XmlElement( name = "employee" )
    public List<Employee> empList;
}

and marshal

        Employee empRoot = ...
        JAXBContext jc = JAXBContext.newInstance( Employee.class );
        Marshaller m = jc.createMarshaller();
        m.marshal( empRoot, XMLOUT );

and unmarshal similarly:
        Employee emp = (Employee)m.unmarshal( new File( XMLIN ) );

-W


On 04/04/2012, wesleywj2 <wesleywj2_at_yahoo.co.uk> wrote:
>
> hi all,
>
> i have this xml:-
>
> <?xml version="1.0" encoding="UTF-8"?>
> <employee id="ROOT">
> <employee id="employee1">
> <employee id="employee2"/>
> <employee id="employee3"/>
> </employee>
> <employee id="employee4">
> <employee id="employee5"/>
> </employee>
> </employee>
>
> and my java object is:-
>
> public class Employee{
> public String id;
> public List<Employee> empList;
>
> public Employee(){
> empList = new ArrayList<Employee>();
> }
> }
>
> how do i convert the Nested xml element to the java object define above?
>
> the case based on above, the final result where the java object will hold is
>
> Employee object has id="ROOT" and its empList will have 2 Employee object
> which id are "employee1" and "employee4" and so on.
>
> I've searched on google, all of the example was meant for simple xml 1 level
> element which can't apply to my case as the xml has nested elements.
>
> can Jaxb convert it?
>
> please advice
>
>
> --
> View this message in context:
> http://old.nabble.com/How-to-unmarshal-nested-xml-element-to-java-object-tp33552969p33552969.html
> Sent from the java.net - jaxb users mailing list archive at Nabble.com.
>
>