您的示例中似乎沒有根元素。你可以做這樣的事情,以獲得您想要的結構: -
@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 {
}
這裏是我的測試代碼: -
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());
...這是打印輸出: -
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<node>
<mainNode>
<node1>node1 value</node1>
<node2>node2 value</node2>
</mainNode>
<mainNode2/>
</node>