Java HTML / XML How to - Insert a xml node as first child in another xml document using dom4j








Question

We would like to know how to insert a xml node as first child in another xml document using dom4j.

Answer

import java.io.StringReader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.dom.DOMDocument;
import org.dom4j.dom.DOMDocumentFactory;
import org.dom4j.io.SAXReader;
/* w  ww  .j  a va 2 s  .com*/
public class Main {
  public static void main(String[] args) throws DocumentException {
    String newNode = "<node>value</node>";
    String text = "<root><given></given></root>";
    DOMDocumentFactory factory = new DOMDocumentFactory();
    SAXReader reader2 = new SAXReader();
    reader2.setDocumentFactory(factory);
    org.dom4j.Document document = reader2.read(new StringReader(text));
    Document newNodeDocument = reader2.read(new StringReader(newNode));

    Element givenNode = document.getRootElement().element("given");
    givenNode.add(newNodeDocument.getRootElement());

    org.dom4j.dom.DOMDocument w3cDoc = (DOMDocument) document;
    org.w3c.dom.Element e = w3cDoc.createElement("div");
    e.setAttribute("id", "someattr");

    w3cDoc.getDocumentElement().getFirstChild().insertBefore(e, w3cDoc.getDocumentElement().getElementsByTagName("node").item(0));
    System.out.println(document.asXML());
  }
}