Java tutorial
//package com.java2s; //License from project: Apache License import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; import org.w3c.dom.Node; public class Main { /** * Will create a documentFragment of the replacingDocument, will import the * replacingDocument as a node of the replacedDocument, and then will * replace the replaceNode with the documentFragment of replacingDocument. * * @param replacedDocument * The document which will have a node replace * @param replacingDocument * The document that will replace a node * @param replacedNode * The node in replacedDocument that will be replaced * @return The new version of replacedDocument will replacedNode replaced */ public static Node replaceNode(final Document replacedDocument, final Document replacingDocument, final Node replacedNode) { // Create a documentFragment of the replacingDocument DocumentFragment docFrag = replacingDocument.createDocumentFragment(); Element rootElement = replacingDocument.getDocumentElement(); docFrag.appendChild(rootElement); // Import docFrag under the ownership of replacedDocument Node replacingNode = ((replacedDocument).importNode(docFrag, true)); // In order to replace the node need to retrieve replacedNode's parent Node replaceNodeParent = replacedNode.getParentNode(); replaceNodeParent.replaceChild(replacingNode, replacedNode); return replacedDocument; } public static Node replaceNode(final Document impD, final Node oldE, final Node newE) { Node parent = oldE.getParentNode(); Node impNewNode = impD.importNode(newE, true); parent.replaceChild(impNewNode, oldE); return parent; } }