1

I want to merge two XML files(source file & temp file) and put the resulted file in the source file and both source and temp files have the same elements but with different values like :

Source.xml:

<Main>
   <source>
        <param>
            <entry>
                <key> bla1 </key>
                <value> bla1 </value>
            </entry> 
        </param>
        <Name> name1 </Name>
   </Source> 
</Main>

And temp.xml:

<Main>
   <source>
        <param>
           <entry>
               <key> bla2 </key>
               <value> bla2 </value>
           </entry>
           <entry>
               <key> bla3 </key>
               <value> bla3 </value>
           </entry>  
        </param>
        <Name> name2 </Name>
   </Source> 
</Main>

And the desired output i want it like :

<Main>
  <source>
        <param>
            <entry>
                <key> bla1 </key>
                <value> bla1 </value>
            </entry> 
        </param>
        <Name> name1 </Name>
   </Source> 
   <source>
        <param>

           <entry>
               <key> bla2 </key>
               <value> bla2 </value>
           </entry>
           <entry>
               <key> bla3 </key>
               <value> bla3 </value>
           </entry>  
        </param>
        <Name> name2 </Name>
   </Source> 
</Main>

I'm using this code but it does't affect the source.xml at all :

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
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;
import org.xml.sax.SAXException;

public class MergeXml {

    private static final String fileName = "Source.xml";
    private static final String tempName = "temp.xml";
    private static final String mainTag = "XmlSource";
    private static final String YES = "yes";


    public void mergeXML() throws ParserConfigurationException, SAXException,
            IOException, TransformerException {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = null;
        Document doc = null;
        Document doc2 = null;

        db = dbf.newDocumentBuilder();
        doc = db.parse(new File(fileName));
        doc2 = db.parse(new File(tempName));
        Element tag = doc.createElement(mainTag);

        NodeList nodeList = doc2.getElementsByTagName("*");

        for(int i =0 ; i < nodeList.getLength(); i++){

            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                String nodeName = node.getNodeName();
                Element tagChild = doc.createElement((nodeName));

                tag.appendChild(tagChild);
            }
        }

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, YES);

        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new StringWriter());
        transformer.transform(source, result);

        BufferedWriter output = new BufferedWriter(new FileWriter(fileName));
        String xmlOutput = result.getWriter().toString();
        output.write(xmlOutput);
        output.close();

    }
}

My XML Original File if needed:

   <XmlSource>
         <hostName>api.worldweatheronline.com</hostName>
         <parameters>
             <entry>
                 <key>num_of_days</key>
                 <value>1</value>
             </entry>
             <entry>
                 <key>q</key>
                 <value>Cairo</value>
            </entry>
            <entry>
                 <key>format</key>
                 <value>xml</value>
            </entry>
            <entry>
                 <key>key</key>
                 <value>wd63kxr294rcgvbynhaf2z4r</value>
            </entry>
       </parameters>
       <URL>
        http://api.worldweatheronline.com/free/v1/weather.ashx?q=Cairo&format=xml&num_of_days=1&key=wd63kxr294rcgvbynhaf2z4r
      </URL>
      <URLPath>/free/v1/weather.ashx</URLPath>

Muhammed Refaat
  • 8,914
  • 14
  • 83
  • 118

3 Answers3

1

Here is the code snippet which you can use to merge two xml.

public static void generateDocument(Document root, Document insertDoc, String toPath, String fromPath) {

    if (null != root) {



        try {
              Node element = getNode(insertDoc, fromPath);
              Node dest = root.importNode(element, true);
            Node node = getNode(root, toPath);
            node.insertBefore(dest, null);
        } catch (Exception ex) {
           System.out.println(ex.getMessage());
        }

    }

}
public Node getNode(Document doc, String strXpathExpression)
            throws ParserConfigurationException, SAXException, IOException,
            XPathExpressionException {

        XPath xpath = XPathFactory.newInstance().newXPath();

        // XPath Query for showing all nodes value
        XPathExpression expr = xpath.compile(strXpathExpression);

        Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);

        return node;
    }

Hence your appraoch would be
1. Create a document obj(obj1) of Soruce.xml
2. Create a document obj(obj2) of test.xml and remove Main tag.

            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            Document doc1 = builder.parse(new File("s1.xml"));
            Document doc2 = builder.parse(new File("s2.xml"));
            generateDocument(doc1,doc2,"/Main", "Main/source");
  1. Call the method mentioned generateDocument(obj1, obj2, "/Main")
Karthik Prasad
  • 9,662
  • 10
  • 64
  • 112
0

Yes its possible to merge xml files. You can refer below links to merge your file. Do necessary changes in code of below links to achieve structure of your XML. Merge Two XML Files in Java

Merging xml file using java NodeList

Merging xml file using java NodeList

Community
  • 1
  • 1
Alpesh Gediya
  • 3,706
  • 1
  • 25
  • 38
0

XML file merge without tag names:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
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;
import org.xml.sax.SAXException;

public class test {

public static void mergeXML(){


    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;
    Document doc = null;
    Document doc2 = null;

    try {
            db = dbf.newDocumentBuilder();
            doc = db.parse(new File("f1.xml"));
            doc2 = db.parse(new File("f2.xml"));
            NodeList ndListFirstFile = doc.getElementsByTagName("staffs");

            Node pndListFirstFile2 = doc2.getElementsByTagName("company").item(0);
            NodeList pchildren = pndListFirstFile2.getChildNodes();
            for(int i=0;i<pchildren.getLength();i++) {
                if(pchildren.item(i).getNodeType() == Node.ELEMENT_NODE) {
                    Element pelem = (Element)pchildren.item(i);
                    // If your document is namespace aware use localName
                    String plocalName = pelem.getLocalName();
                    // Tag name returns the localName and the namespace prefix
                    String ptagName= pelem.getTagName();
                    // do stuff with the children
                    System.out.print(ptagName);
                   Node ndListFirstFile2 = doc2.getElementsByTagName(ptagName).item(0);
                    NodeList children = ndListFirstFile2.getChildNodes();
                     for(int ii=0;ii<children.getLength();ii++) {
                        if(children.item(ii).getNodeType() == Node.ELEMENT_NODE) {
                            Element elem = (Element)children.item(ii);
                            // If your document is namespace aware use localName
                            String localName = elem.getLocalName();
                            // Tag name returns the localName and the namespace prefix
                            String tagName= elem.getTagName();
                            // do stuff with the children
                            System.out.print(tagName);
                            Node nodeArea = doc.importNode(doc2.getElementsByTagName(tagName).item(0), true);
                            ndListFirstFile.item(0).appendChild(nodeArea);
                        }
                    }
                }
            }



          TransformerFactory tFactory = TransformerFactory.newInstance();
          Transformer transformer = tFactory.newTransformer();
          transformer.setOutputProperty(OutputKeys.INDENT, "yes");  

          DOMSource source = new DOMSource(doc);
          StreamResult result = new StreamResult(new StringWriter());
          transformer.transform(source, result); 

          Writer output = new BufferedWriter(new FileWriter("f3.xml"));
          String xmlOutput = result.getWriter().toString();  
          output.write(xmlOutput);
          output.close();

    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, TransformerException{
    mergeXML();
}

}

Ananthakumar
  • 323
  • 1
  • 14