Moving Nodes between DOM Documents by Copying a Node from One Parse Tree into Another in Java
Description
The following code shows how to moving Nodes between DOM Documents by Copying a Node from One Parse Tree into Another.
Example
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/*from w w w.j a v a 2 s .c o m*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
public class Main {
static public void main(String[] arg) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
dbf.setNamespaceAware(true);
dbf.setIgnoringElementContentWhitespace(true);
Document doc = null;
try {
DocumentBuilder builder = dbf.newDocumentBuilder();
InputSource is = new InputSource("personWithDTD.xml");
doc = builder.parse(is);
importName(doc, doc);
} catch (Exception e) {
System.err.println(e);
}
}
public static void importName(Document doc1,Document doc2) {
Element root1 = doc1.getDocumentElement();
Element personInDoc1 = (Element)root1.getFirstChild();
Node importedPerson = doc2.importNode(personInDoc1,true);
Element root2 = doc2.getDocumentElement();
root2.appendChild(importedPerson);
}
}
<locations>
<place>
<name>oldName</name>
<directions>oldDirection</directions>
</place>
</locations>
]]>
</code>
<result><![CDATA[
<?xml version="1.0" standalone="yes"?>
<locations>
<place>
<name>
oldName
</name>
<directions>
oldDirection
</directions>
</place>
<place>
<name>
oldName
</name>
<directions>
oldDirection
</directions>
</place>
</locations>