我想生成如下所示的 XML:

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

最佳答案

您的示例中似乎没有根元素。你可以做这样的事情来获得你想要的结构:-

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

关于java - JAXB : XmlElementWrapper nested nodes,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5099170/

10-12 04:30