Java HTML / XML How to - Merge xml document and keep necessary namespace declarations


We would like to know how to merge xml document and keep necessary namespace declarations.


/*w  w  w  . j  a  v  a  2  s  .  c  o m*/
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;

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

public class Main {

  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    File file1 = new File("input1.xml");
    Document doc1 = db.parse(file1);
    Element rootElement1 = doc1.getDocumentElement();

    File file2 = new File("input2.xml");
    Document doc2 = db.parse(file2);
    Element rootElement2 = doc2.getDocumentElement();

    // Copy Attributes
    NamedNodeMap namedNodeMap2 = rootElement2.getAttributes();
    for (int x = 0; x < namedNodeMap2.getLength(); x++) {
      Attr importedNode = (Attr) doc1.importNode(namedNodeMap2.item(x), true);

    // Copy Child Nodes
    NodeList childNodes2 = rootElement2.getChildNodes();
    for (int x = 0; x < childNodes2.getLength(); x++) {
      Node importedNode = doc1.importNode(childNodes2.item(x), true);

    // Output Document
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    DOMSource source = new DOMSource(doc1);
    StreamResult result = new StreamResult(System.out);
    t.transform(source, result);