Java HTML / XML How to - Merge Documents while preserving xsi:type








Question

We would like to know how to merge Documents while preserving xsi:type.

Answer

import java.io.File;
//from   ww w  . j ava 2s.co  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 javax.xml.transform.stream.StreamResult;

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();
    dbf.setNamespaceAware(true);
    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 Child Nodes
    NodeList childNodes2 = rootElement2.getChildNodes();
    for (int x = 0; x < childNodes2.getLength(); x++) {
      Node importedNode = doc1.importNode(childNodes2.item(x), true);
      if (importedNode.getNodeType() == Node.ELEMENT_NODE) {
        Element importedElement = (Element) importedNode;
        // Copy Attributes
        NamedNodeMap namedNodeMap2 = rootElement2.getAttributes();
        for (int y = 0; y < namedNodeMap2.getLength(); y++) {
          Attr importedAttr = (Attr) doc1.importNode(namedNodeMap2.item(y),
              true);
          importedElement.setAttributeNodeNS(importedAttr);
        }
      }
      rootElement1.appendChild(importedNode);
    }

    // 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);
  }

}