Copy a Subtree of Nodes in a DOM Document in Java
Description
The following code shows how to copy a Subtree of Nodes in a DOM Document.
Example
import java.io.StringReader;
/*ww w . ja va 2s . co m*/
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
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);
Element dup = (Element) element.cloneNode(true);
element.getParentNode().insertBefore(dup, element.getNextSibling());
}
}
The code above generates the following result.