使用Java将两个XML文件合并为一个XML文件

时间:2012-04-11 17:20:01

标签: java xml merge io

我坚持如何继续组合两个不同的XML文件(具有相同的结构)。当我对它进行一些研究时,人们会说必须使用像DOM或StAX这样的XML解析器。但我不能用常规IOStream做到这一点?我目前正试图在IOStream的帮助下做,但这不是解决我的目的,它更复杂。

例如,我尝试的是;

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

我请您通过添加其他内容告诉我如何继续合并两个XML文件。如果您能为我提供一些示例链接,那将是很棒的。!

提前谢谢你..!               的System.out.println(strLine1);               }

}

3 个答案:

答案 0 :(得分:1)

不完全确定您要做什么。通过合并你的意思是:

一个。您想要合并2个DOM的内容,并提出一个带有附加节点的对象模型(有效的)

湾您希望一个接一个地合并这两个文件,而不关心实际内容

如果是a,请使用XML解析器。当然你可以手工编写这个东西并尝试将流处理成dom对象,但是你将重写那些解析器的大部分内容。为什么要重写已存在的东西。

如果是b,那就做一个愚蠢的副本。复制第一个文件(再次使用实用程序,例如apache common的FileUtil允许你复制文件。除非必要,不要写),打开复制文件的IO流,然后读取和写入第二个文件。

答案 1 :(得分:1)

作为一般规则,永远不要在词法层面上进行任何XML处理:始终使用XML解析器。 (如果(a)您是XML专家,那么您可以违反此规则,因此您知道可能出现的问题,并且(b)您知道结果不一定是正确的。)

其次,执行此类处理的最简单方法是使用为作业设计的语言,如XSLT或XQuery。使用Java使它非常适合猪油。

如果您对要合并的文件类型以及您希望输出的外观更具体,我们可以为您提供更准确的答案。

答案 2 :(得分:0)

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

    }
}