Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB : XmlElementWrapper nested nodes

Tags:

java

jaxb

I want to Generate XML that look like this :

    <mainNode>   
       <node1></node1> 
       <node2></node2> 
    </mainNode>
   <mainNode2></mainNode2> 

and this is how i generate the mainNode1 , mainNode2 and node1 in my code:

   @XmlElementWrapper(name = "mainNode")
        @XmlElement(name = "node1")
        public List<String> getValue() {
            return value;
        }

   @XmlElement(name = "mainNode2")
   public String getValue2() {
   return value2;
   }

how i could add node2 to the mainNode1 ?

like image 210
Jimmy Avatar asked Feb 24 '11 00:02

Jimmy


2 Answers

XmlElementWrapper should be used only when the wrapperElement has a list of same type of elements.

<node> 
   <idList>
       <id> value-of-item </id>
       <id> value-of-item </id>
       ....
   </idList>
</node>

 @XmlAccessorType(XmlAccessType.FIELD)
 @XmlRootElement
 class Node {
    @XmlElementWrapper(name = "idList")
    @XmlElement(name = "id", type = String.class)
    private List<String> ids = new ArrayList<String>;
 //GETTERS/SETTERS
 }
like image 192
Kanagavelu Sugumar Avatar answered Sep 20 '22 03:09

Kanagavelu Sugumar


You don't seem to have a root element in your example. You could do something like this to obtain the structure you want:-

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
class Node {
    private MainNode    mainNode;
    private MainNode2   mainNode2;

    public Node() {
    }

    public Node(MainNode mainNode, MainNode2 mainNode2) {
        this.mainNode = mainNode;
        this.mainNode2 = mainNode2;
    }

}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
class MainNode {
    private String  node1;
    private String  node2;

    public MainNode() {
    }

    public MainNode(String node1, String node2) {
        this.node1 = node1;
        this.node2 = node2;
    }

}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
class MainNode2 {

}

Here's my test code:-

JAXBContext jc = JAXBContext.newInstance(Node.class);
Marshaller m = jc.createMarshaller();

MainNode mainNode = new MainNode("node1 value", "node2 value");
MainNode2 mainNode2 = new MainNode2();
Node node = new Node(mainNode, mainNode2);

StringWriter sw = new StringWriter();

m.marshal(node, sw);

System.out.println(sw.toString());

... and here's the printout:-

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<node>
  <mainNode> 
    <node1>node1 value</node1>
    <node2>node2 value</node2>
  </mainNode>
  <mainNode2/>
</node>
like image 37
limc Avatar answered Sep 24 '22 03:09

limc