Apr 02

To insert a new root node into an existing DOM Document involves creating a new DOM Document with the required new root node, and then copying in the existing DOM Document into the new root.

The following code snippets shows an outline of the code involved.


DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document existingdoc = builder.parse(file);

// Create an empty document

Document doc = builder.newDocument();

// Add the new root node

Element root = doc.createElement("Objects");
doc.appendChild(root);

// Add a copy of the nodes from existing document

Node copy = doc.importNode(existingdoc.getDocumentElement(), true);
root.appendChild(copy);

written by objects \\ tags: , ,


3 Responses to “How to insert new root Node in XML DOM Document?”

  1. Ujjal Says:

    Are you sure on
    [code]Element copy = doc.importNode(existingdoc.getDocumentElement(), true);[/code]
    this line? here is an error I think.

  2. Martin Hansson Says:

    I believe row 16 should be Node instead of Element: “Node copy = doc.importNode(existingdoc.getDocumentElement(), true);” since importNode(9 returns a Node and appendChild() takes a Node as argument.

    But I could be wrong 🙂

  3. objects Says:

    Thanks for spotting that, have updated the code

Leave a Reply

You must be logged in to post a comment.