Wednesday, April 11, 2007

Copying a Subtree of Nodes in a DOM Document

e525. Copying a Subtree of Nodes in a DOM Document

    // Obtain an element; the following method is implemented in
// e510 The Quintessential Program to Create a DOM Document from an XML File Document doc = parseXmlFile("infilename.xml", false);
NodeList list = doc.getElementsByTagName ("entry");
Element element = (Element)list.item(0);

// Make a copy of the element, including any child nodes
Element dup = (Element)element.cloneNode(true);

// Insert the copy immediately after the cloned element
element.getParentNode().insertBefore(dup, element.getNextSibling());
This is the sample input for the example:
    <root>
<entry attr="value">
a<i>b</i>c
</entry>
</root>
This is the resulting XML:
    <?xml version="1.0" encoding="UTF-8"?>
<root>
<entry attr="value">
a<i>b</i>c
</entry>
<entry attr="value">
a<i>b</i>c
</entry>
</root>

My samples: copy a whole tree from one xml file to aother xml file doc:

private static Document buildReturnDoc(long txnID, Document doc){
Document document=null;
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.newDocument();

Element root = (Element) document.createElementNS(null, "transaction");
root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "dncg");
document.appendChild(root);
root.setAttribute("trxID", String.valueOf(txnID));

Node node=document.importNode(getIncomingRequestElement(doc), true);
root.appendChild(node);

//DNCGUtils.writeXmlDoc("Transaction-output.xml", doc);
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
}

return document;
}


private static Element getIncomingRequestElement(Document doc){

Element fd=null;
Element dup=null;
fd=(Element) doc.getElementsByTagName("incoming-request").item(0);
dup=(Element) fd.cloneNode(true);

return dup;
}

No comments: