title: Java XML Insert a parent node
body: <p>I have the following xml</p>
  
  <pre><code>&lt;Root&gt;
      &lt;Page&gt;
          &lt;Object ref="a"&gt;&lt;/Object&gt;
          &lt;Object ref="b"&gt;&lt;/Object&gt;
      &lt;/Page&gt;
  &lt;/Root&gt;
  </code></pre>
  
  <p>I want to convert into </p>
  
  <pre><code>&lt;Root&gt;
      &lt;Page&gt;
          &lt;ObjectGroup ref="a"&gt;
              &lt;Object ref="a"/&gt;
          &lt;/ObjectGroup&gt;
          &lt;ObjectGroup ref="b"&gt;
              &lt;Object ref="b"/&gt;
          &lt;/ObjectGroup&gt;
      &lt;/Page&gt;
  &lt;/Root&gt;
  </code></pre>
  
  <p>Basically I want to introduce a new parent node. I used the below way but it's introducing more parents</p>
  
  <pre><code> private static void loadRoots(String xMLPath) {
          Document doc = Migrate.initTreeOpFromString(xMLPath);
          Element rootElement = doc.getDocumentElement();
          loadPage(rootElement);
          Migrate.finishTreeOp(doc, "D:\\a.xml");
      }
  
      private static void loadPage(Element root) {
          NodeList pageNodes = root.getChildNodes();
          for (int j = 0; j &lt; pageNodes.getLength(); j++) {
              Node pageNode = pageNodes.item(j);
              if (pageNode.getNodeType() == Node.ELEMENT_NODE) {
                  loadObject((Element) pageNode);
              }
          }
      }
  
      private static void loadObject(Element pageNode) {
          NodeList objectNodes = pageNode.getChildNodes();
          for (int j = 0; j &lt; objectNodes.getLength(); j++) {
              Node objectNode = objectNodes.item(j);
              if (objectNode.getNodeType() == Node.ELEMENT_NODE) {
                  Element objGroup = pageNode.getOwnerDocument().createElement("ObjectGroup");
                  String ref = objectNode.getAttributes().getNamedItem("ref").getTextContent();
                  objGroup.setAttribute("ref", ref);
                  pageNode.removeChild(objectNode);
                  objGroup.appendChild(objectNode);
                  pageNode.appendChild(objGroup);
              }
          }
      }
  </code></pre>
  
  <p>But the output for this is</p>
  
  <pre><code>&lt;Root&gt;
      &lt;Page&gt;
          &lt;ObjectGroup ref="b"&gt;
              &lt;Object ref="b"/&gt;
          &lt;/ObjectGroup&gt;
          &lt;ObjectGroup ref="a"&gt;
              &lt;ObjectGroup ref="a"&gt;
                  &lt;ObjectGroup ref="a"&gt;
                      &lt;Object ref="a"/&gt;
                  &lt;/ObjectGroup&gt;
              &lt;/ObjectGroup&gt;
          &lt;/ObjectGroup&gt;
      &lt;/Page&gt;
  &lt;/Root&gt;
  </code></pre>
  
  <p>which is not what I wanted. How do I solve this</p>