简体   繁体   中英

Merging two XML files into one XML file using Java

I am stuck with how to proceed with combining two different XML files(which has the same structure). When I was doing some research on it, people say that XML parsers like DOM or StAX will have to be used. But cant I do it with the regular IOStream? I am currently trying to do with the help of IOStream but this is not solving my purpose, its being more complex.

For example, What I have tried is;

               public class GUI {

           public static void main(String[] args) throws Exception {

           // Creates file to write to
           Writer output = null;
           output = new BufferedWriter(new   FileWriter("C:\\merged.xml"));
           String newline = System.getProperty("line.separator");

           output.write("");

           // Read in xml file 1
           FileInputStream in = new FileInputStream("C:\\1.xml");
           BufferedReader br = new BufferedReader(new InputStreamReader(in));
           String strLine;

           while ((strLine = br.readLine()) != null) {

           if (strLine.contains("<MemoryDump>")){
           strLine = strLine.replace("<MemoryDump>", "xmlns:xsi");
           }
           if (strLine.contains("</MemoryDump>")){
           strLine = strLine.replace("</MemoryDump>", "xmlns:xsd");
          }

          output.write(newline);
          output.write(strLine);

          System.out.println(strLine);
          }

           // Read in xml file 2
           FileInputStream in = new FileInputStream("C:\\2.xml");
           BufferedReader br1 = new BufferedReader(new InputStreamReader(in));
           String strLine1;

           while ((strLine1 = br1.readLine()) != null) {

           if (strLine1.contains("<MemoryDump>")){
           strLine1 = strLine1.replace("<MemoryDump>", "");
           }
           if (strLine1.contains("</MemoryDump>")){
           strLine1 = strLine1.replace("</MemoryDump>", "");
          }

          output.write(newline);
          output.write(strLine1);

I request you to kindly let me know how do I proceed with merging two XML files by adding additional content as well. It would be great if you could provide me some example links as well..!

Thank You in Advance..! System.out.println(strLine1); }

}

Not exactly sure what you're looking to do. By merging do you mean:

a. You want to merge the content for the 2 DOMs and come up with one object model (a valid one) with appended nodes

b. You want to merge the 2 files one after the other and not care about the actual content

If it's a, use XML parsers. Sure you can write the thing by hand and try to process the streams into dom objects but you'll be rewriting a lot of what those parsers are for. Why rewrite something that's already there.

If it's b, just do a dumb copy. Copy the first file (use utilities again, stuff like apache common's FileUtil allows you to copy files. Don't write unless necessary), open an IO stream to the copied file then read and write the second file over.

As a general rule, never do any processing of XML at the lexical level: always use an XML parser. (You can break this rule if (a) you are an XML expert, so you know what might go wrong, and (b) you know that the results don't have to be correct all the time.)

Secondly, the easiest way to do this kind of processing is to use a language designed for the job, like XSLT or XQuery. Using Java makes it very lard work.

If you're more specific about the kind of files you want merged and what you want the output to look like, we can give you a more precise answer.

package com.cts.sterling.order;

//package com.academy.ecommerce.sterling.userexits;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.cts.sterling.custom.accelerators.util.XMLUtil;


public class MergeXml {

    public static Document mergeXml(Document doc1, Document doc2)

            throws Exception {

        // Getting the attributes of OrderLine from document2 and document1
        NodeList objOrderLineList2 = doc2.getElementsByTagName("OrderLine");
        NodeList objOrderLineList1 = doc1.getElementsByTagName("OrderLine");

        // Creating Element for OrderLine
        Element eleOrderline2 = (Element) objOrderLineList2.item(0);
        Element eleOrderline1 = (Element) objOrderLineList1.item(0);

        // Declaring attributes as String array 
        String[] Line1={"LineType","LevelOfService"};

        // Copying attributes from document2 to document1
        XMLUtil.copyAttributes(eleOrderline2, eleOrderline1, Line1);

        // Getting the attributes of Extn from document2 and document1
        NodeList objExtn2 = doc2.getElementsByTagName("Extn");
        NodeList objExtn1 =doc1.getElementsByTagName("Extn");

        // Creating Element for Extn
        Element eleExtn2 = (Element) objExtn2.item(0);
        Element eleExtn1 = (Element) objExtn1.item(0);

        // Declaring attributes as String array
        String[] Line2={"ExtnMediaCode","ExtnLastName","ExtnGroupID"};

        // Copying attributes from document2 to document1
        XMLUtil.copyAttributes(eleExtn2, eleExtn1, Line2);

        // Getting the attributes of WSIAddnlOrderLineData from document2 and document1
        NodeList objAddln2 = doc2.getElementsByTagName("WSIAddnlOrderLineData");
        NodeList objAddln1 =doc1.getElementsByTagName("WSIAddnlOrderLineData");

        // Creating Element for WSIAddnlOrderLineData
        Element eleAddln2 = (Element) objAddln2.item(0);
        Element eleAddln1 = (Element) objAddln1.item(0);

        // Declaring attributes as String array
        String[] Line3 ={"ExtnShipMode" , "ExtnDeliverTogether","ExtnComponentReplacementIndicator","ExtnGiftCardRequiredIndicator","ExtnReplOriginalItemID", 
                "ExtnSpecialHandlingIndicator","ExtnSpecialHandlingReasonCode","ExtnCardType","ExtnCardClass","ExtnEcomSuborderNo","ExtnEcomOrderLineNo",
                "ExtnPFSFlag","ExtnSVCCarrierServiceCode","ExtnSVCSCAC","ExtnSVCUpgradeFlag","ExtnSVCSKUType","ExtnSVCTo","ExtnSVCFrom"};   

        // Copying attributes from document2 to document1
        XMLUtil.copyAttributes(eleAddln2, eleAddln1, Line3);

        // Getting the attributes of Instruction from document2 and document1
        NodeList objInst2 = doc2.getElementsByTagName("Instruction");
        NodeList objInst1 =doc1.getElementsByTagName("Instruction");

        // Creating Element for Instruction
        Element eleInst2 = (Element) objInst2.item(0);
        Element eleInst1 = (Element) objInst1.item(0);

        // Declaring attributes as String array
        String[] Line4 ={"InstructionText","InstructionType","SequenceNo","InstructionURL","InstructionUsage"}; 

        // Copying attributes from document2 to document1
        XMLUtil.copyAttributes(eleInst2, eleInst1, Line4);

        //Printing output document
        System.out.println(XMLUtil.getString(doc1));
        return doc1;

    }
    //Main method
    public static void main(String[] args) {
        try{

            File file1 = new File("D:/Handson/merge1.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc1 = dBuilder.parse(file1);
            File file2 = new File("D:/Handson/merge2.xml");
            Document doc2 = dBuilder.parse(file2);

            //calling the method
            mergeXml(doc1,doc2);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM