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);
Array ( ) 3 Responses to “How to insert new root Node in XML DOM Document?”
Leave a Reply
You must be logged in to post a comment.
July 3rd, 2012 at 7:19 pm
Are you sure on
[code]Element copy = doc.importNode(existingdoc.getDocumentElement(), true);[/code]
this line? here is an error I think.
November 15th, 2012 at 1:42 am
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 🙂
November 15th, 2012 at 1:37 pm
Thanks for spotting that, have updated the code