Copying nodes between XML documents with Java DOM

|
A recurent problem in Java is to copy nodes from one Document to another one ( org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it). This issue could be done easily by using the Document.importNode method.

bais = new ByteArrayInputStream(donnees);

Document o_doc; // original document
Document r_doc; // resulting document

DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setNamespaceAware(false);

// Creation du gestionnaire de DOM
DocumentBuilder builder = dfactory.newDocumentBuilder();

o_doc = builder.parse(bais);
r_doc = builder.newDocument();

Element root = r_doc.createElement("Root");
root.setAttribute("xmlns", "http://my.domain.com");
Element oneNode = r_doc.createElement("oneNode");
root.appendChild(oneNode);

r_doc.appendChild(root);

CachedXPathAPI cxpa = new CachedXPathAPI();

Node nodeToCopy = cxpa.selectSingleNode(o_doc, "XPathPathToNodeToCopy");
// use importNode to copy into another tree
oneNode.appendChild(r_doc.importNode(nodeToCopy, true));

Copy one node to one parse Tree into another, Copy a node into a new Document, Copy parts of an xml document into another, Nodes copy in Java, Copy XML nodes in Java