Copy a Subtree of Nodes from One DOM Document to Another in Java
Description
The following code shows how to copy a Subtree of Nodes from One DOM Document to Another.
Example
// w ww . ja v a 2 s . c om
import java.io.File;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class Main {
public static void main(String[] argv) throws Exception {
StringReader sr = new StringReader("<tag>java2s.com</tag>");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder loader = factory.newDocumentBuilder();
Document document = loader.parse(new InputSource(sr));
NodeList list = document.getElementsByTagName("tag");
Element element = (Element) list.item(0);
Document doc2 = factory.newDocumentBuilder().parse(new File("another.xml"));
Node dup = doc2.importNode(element, true);
doc2.getDocumentElement().appendChild(dup);
}
}