DOM

Copy nodes subtree from one DOM document to another

In this example we shall show you how to copy the Nodes Subtree from one DOM Document to another. We have implemented a method, that is void prettyPrint(Document xml), in order to convert a DOM into a formatted XML String. To copy the Nodes Subtree from one DOM Document to another one should perform the following steps:

  • Obtain a new instance of a DocumentBuilderFactory, that is a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.
  • Set the parser produced so as not to validate documents as they are parsed, using setValidating(boolean validating) API method of DocumentBuilderFactory, with validating set to false.
  • Create a new instance of a DocumentBuilder, using newDocumentBuilder() API method of DocumentBuilderFactory.
  • Get the two DOM Document objects from the xml files, using parse(InputStream is) API method of DocumentBuilder.
  • Call void prettyPrint(Document xml) method of the example to see the second Document, before coping the nodes from the first one to it. The method gets the xml Document and converts it into a formatted xml String, after transforming it with specific parameters, such as encoding. The method uses a Transformer, that is created using newTransformer() API method of TransformerFactory. The Transformer is used to transform a source tree into a result tree. After setting specific output properties to the transformer, using setOutputProperty(String name, String value) API method of Transformer, the method uses it to make the transformation, with transform(Source xmlSource, Result outputTarget) API method of Transformer. The parameters are the DOMSource with the DOM node and the result that is a StreamResult created from a StringWriter,
  • Get the NodeList of all the Elements in the first document with a given tag name, using getElementsByTagName(String tagname) API method of Document, and from this nodeList get the first Element.
  • Call importNode(Node importedNode, boolean deep) of the second Document, using as parameters the first element from the first Document, in order to import the node from the first document to this document.
  • Add the above copied node to the end of the list of children of the second Document. Call getDocumentElement() API method of the second Document to get this Document’s Element and then using appendChild(Node newChild) API method of Element append the above copied Node to this element,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class CopyNodesSubtreeFromOneDOMDocumentToAnother {
	
	public static void main(String[] args) throws Exception {
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setValidating(false);
		DocumentBuilder db = dbf.newDocumentBuilder();
		
		Document doc1 = db.parse(new FileInputStream(new File("in1.xml")));
		Document doc2 = db.parse(new FileInputStream(new File("in2.xml")));
		
		System.out.println("Before Copy...");
		prettyPrint(doc2);
		
		NodeList list = doc1.getElementsByTagName("channel");
		Element element = (Element) list.item(0);

		// Imports a node from another document to this document, without altering 
	    // or removing the source node from the original document
		Node copiedNode = doc2.importNode(element, true);

		// Adds the node to the end of the list of children of this node
		doc2.getDocumentElement().appendChild(copiedNode);
		
		System.out.println("After Copy...");
		prettyPrint(doc2);
		
	}
	
	public static final void prettyPrint(Document xml) throws Exception {
		Transformer tf = TransformerFactory.newInstance().newTransformer();
		tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		tf.setOutputProperty(OutputKeys.INDENT, "yes");
		Writer out = new StringWriter();
		tf.transform(new DOMSource(xml), new StreamResult(out));
		System.out.println(out.toString());
	}

}

Input:

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title>Java Tutorials and Examples 1</title>
		<language>en-us</language>
		<item>
			<title><![CDATA[Java Tutorials 1]]></title>
			<link>http://www.javacodegeeks.com/</link>
		</item>
		<item>
			<title><![CDATA[Java Examples 1]]></title>
			<link>http://examples.javacodegeeks.com/</link>
		</item>
	</channel>
</rss>
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title>Java Tutorials and Examples 2</title>
		<language>en-us</language>
		<item>
			<title><![CDATA[Java Tutorials 2]]></title>
			<link>http://www.javacodegeeks.com/</link>
		</item>
		<item>
			<title><![CDATA[Java Examples 2]]></title>
			<link>http://examples.javacodegeeks.com/</link>
		</item>
	</channel>
</rss>

Output:

Before Copy...
<rss version="2.0">
	<channel>
		<title>Java Tutorials and Examples 2</title>
		<language>en-us</language>
		<item>
			<title><![CDATA[Java Tutorials 2]]></title>
			<link>http://www.javacodegeeks.com/</link>
		</item>
		<item>
			<title><![CDATA[Java Examples 2]]></title>
			<link>http://examples.javacodegeeks.com/</link>
		</item>
	</channel>
</rss>

After Copy...
<rss version="2.0">
	<channel>
		<title>Java Tutorials and Examples 2</title>
		<language>en-us</language>
		<item>
			<title><![CDATA[Java Tutorials 2]]></title>
			<link>http://www.javacodegeeks.com/</link>
		</item>
		<item>
			<title><![CDATA[Java Examples 2]]></title>
			<link>http://examples.javacodegeeks.com/</link>
		</item>
	</channel>
<channel>
		<title>Java Tutorials and Examples 1</title>
		<language>en-us</language>
		<item>
			<title><![CDATA[Java Tutorials 1]]></title>
			<link>http://www.javacodegeeks.com/</link>
		</item>
		<item>
			<title><![CDATA[Java Examples 1]]></title>
			<link>http://examples.javacodegeeks.com/</link>
		</item>
	</channel>
</rss>

  
This was an example of how to copy the Nodes Subtree from one DOM Document to another in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button