2011-02-24 173 views
7

我要生成XML看起來像這樣的:JAXB:XmlElementWrapper嵌套節點

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

,這是我如何生成mainNode1,mainNode2並且node1在我的代碼:

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

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

我怎麼可以添加node2到mainNode1?

回答

5

您的示例中似乎沒有根元素。你可以做這樣的事情,以獲得您想要的結構: -

@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> 
7

僅當wrapperElement具有相同類型的元素的列表時才應使用XmlElementWrapper。

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