JAXB: XmlElementWrapper subnodes

I want to create an XML that looks like this:

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

and this is how I generate 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 can I add node2 to mainNode1?

+7
source share
2 answers

You don't seem to have a root element in your example. You can do something like this to get the structure you need: -

 @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 is 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 is the listing: -

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <node> <mainNode> <node1>node1 value</node1> <node2>node2 value</node2> </mainNode> <mainNode2/> </node> 
+5
source

XmlElementWrapper should only be used when there is a list of elements of the same type in the wrapperElement element.

 <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 } 
+7
source

All Articles