Question

I have the following document model structure.

<rootNode>
  <node1>someValue</node1>
  <node2>someValue</node2>
  <groupOfNodes>
     <groupNode>
        <node3>someValue</node3>
        <node4>someValue</node4>
     </groupNode>
     <groupNode>
        <node3>someValue</node3>
        <node4>someValue</node4>
     </groupNode>
     <groupNode>
        <node3>someValue</node3>
        <node4>someValue</node4>
     </groupNode>
  </groupOfNodes>
</rootNode>

I have figured out how to map node1 and node2 to an annotated POJO and they work perfectly. However, I am kind of stuck on how to bind the nested nodes in groupOfNodes to a List of groupNodes. This is what I have so far. I went through the available annotations list on the java docs and I found that @XmlList and @XmlElementWrapper may be the closest to what I am wanting but I am not sure how to use them in this context. When I put @XmlElementWrapper I get null in groupNodesList. When I put @XmlList I get an exception saying that GroupNode is a complex type to be put under @XmlList.

@XmlRootElement(name="rootNode")
@XmlAccessorType(XmlAccessType.FIELD)
public class MyNodes {
      @XmlElement(name="node1", required=false)
    private String node1;
    @XmlElement(name="node2", required=false)
    private String node2;   
     //tried this for the nested nodes but groupNodesList is always empty
       @XmlElementWrapper
  @XmlElement(name="groupOfNodes", required=false)
  private List<GroupNode> groupNodesList;
       //getters setters  

} 


   @XmlRootElement
   @XmlAccessorType(XmlAccessType.FIELD)
    public class GroupNode {
       @XmlElement(name="node3", required=false)
        private String node3;
        @XmlElement(name="node4", required=false)
        private String node4;             
         //getters setters  
    } 

Should I be using XPath instead? If possible I would like to see a code example using standard JAXB2. Otherwise some hints would be great too.

I appreciate it!

Was it helpful?

Solution

The following is what you need:

@XmlElementWrapper(name="groupOfNodes")
@XmlElement(name="groupNode")   
private List<GroupNode> groupNodesList;

For more information on JAXB and collections see:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top