开发者

JAXB : XmlElementWrapper nested nodes

开发者 https://www.devze.com 2023-02-13 06:02 出处:网络
I want to Generate XML that look like this : <mainNode> <node1></node1> <node2></node2>

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:

   @开发者_C百科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 ?


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
 }


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

精彩评论

暂无评论...
验证码 换一张
取 消