This code uses XStream and generates the output you are looking for.
The node class:
import java.util.ArrayList; import java.util.List; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.annotations.XStreamImplicit; @XStreamAlias("Node") public class Node { @XStreamAsAttribute private String name; @XStreamImplicit private List<Node> nodes = new ArrayList<Node>(); public Node(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Node> getNodes() { return nodes; } public void setNodes(List<Node> nodes) { this.nodes = nodes; } public void addNode(Node n) { nodes.add(n); } }
The Main class:
import com.thoughtworks.xstream.XStream; public class NodeXStream { public static void main(String[] args) { Node n1 = new Node("1"); Node n2 = new Node("2"); Node n3 = new Node("3"); Node n4 = new Node("4"); Node n5 = new Node("5"); n1.addNode(n2); n1.addNode(n3); n2.addNode(n4); n3.addNode(n5); XStream xs = new XStream(); xs.processAnnotations(Node.class); // To XML String myXML = xs.toXML(n1); // From XML Node newNode = (Node) xs.fromXML(myXML); } }
EDIT: Added the deserialization code.
To deserialize you'll also need to add the XPP3 library to the build path. It is part of XStream.