如何在Java中合并两个XML

时间:2011-04-15 19:46:17

标签: java xml merge stax

我正在尝试在Java中合并两个xmls。我正在使用STaX API来编写这些XML。我在互联网上搜索了很多关于如何合并xmls的内容,但没有一个像C#那样直截了当。使用StAX在Java中有没有直接的方法?可能xslt不是正确的解决方案,因为文件大小可能很大。

File1.xml

<TestCaseBlock>
    <TestCase TestCaseID="1">
        <Step ExecutionTime="2011-03-29 12:08:31 EST">
            <Status>Passed</Status>
            <Description>foo</Description>
            <Expected>foo should pass</Expected>
            <Actual>foo passed</Actual>
        </Step>
       </TestCase>
</TestCaseBlock> 

File2.xml

<TestCaseBlock>
    <TestCase TestCaseID="2">
        <Step ExecutionTime="2011-03-29 12:08:32 EST">
            <Status>Failed</Status>
            <Description>test something</Description>
            <Expected>something expected</Expected>
            <Actual>not as expected</Actual>
        </Step>
    </TestCase>
</TestCaseBlock>

Merged.xml

<TestCaseBlock>
<TestCase TestCaseID="1">
    <Step ExecutionTime="2011-03-29 12:08:33 EST">
        <Status>Passed</Status>
        <Description>foo</Description>
        <Expected>foo should pass</Expected>
        <Actual>foo passed</Actual>
    </Step>
</TestCase>
<TestCase TestCaseID="2">
    <Step ExecutionTime="2011-03-29 12:08:34 EST">
        <Status>Failed</Status>
        <Description>test something</Description>
        <Expected>something expected</Expected>
        <Actual>not as expected</Actual>
    </Step>
</TestCase>
</TestCaseBlock>

6 个答案:

答案 0 :(得分:3)

我有一个适合我的解决方案。现在是专家,请告知这是否可行。

谢谢, -Nilesh

    XMLEventWriter eventWriter;
    XMLEventFactory eventFactory;
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream("testMerge1.xml"));
    eventFactory = XMLEventFactory.newInstance();
    XMLEvent newLine = eventFactory.createDTD("\n");                
    // Create and write Start Tag
    StartDocument startDocument = eventFactory.createStartDocument();
    eventWriter.add(startDocument);
    eventWriter.add(newLine);
    StartElement configStartElement = eventFactory.createStartElement("","","TestCaseBlock");
    eventWriter.add(configStartElement);
    eventWriter.add(newLine);
    String[] filenames = new String[]{"test1.xml", "test2.xml","test3.xml"};
    for(String filename:filenames){
           XMLEventReader test = inputFactory.createXMLEventReader(filename,
                             new FileInputStream(filename));
        while(test.hasNext()){
            XMLEvent event= test.nextEvent();
        //avoiding start(<?xml version="1.0"?>) and end of the documents;
        if (event.getEventType()!= XMLEvent.START_DOCUMENT && event.getEventType() != XMLEvent.END_DOCUMENT)
                eventWriter.add(event);         
        eventWriter.add(newLine);
            test.close();
        }           
    eventWriter.add(eventFactory.createEndElement("", "", "TestCaseBlock"));
    eventWriter.add(newLine);
    eventWriter.add(eventFactory.createEndDocument());
    eventWriter.close();

答案 1 :(得分:2)

通用解决方案仍然是XSLT,但是您需要首先将两个文件合并为一个大型XML,并使用包装器元素(XSLT使用一个输入源)。

<root>
    <TestCaseBlock>
        <TestCase TestCaseID="1">
        ...
        </TestCase>
    </TestCaseBlock>
    <TestCaseBlock>
        <TestCase TestCaseID="2">
        ...
        </TestCase>
    </TestCaseBlock>
</root>

然后只需为match =“// TestCase”执行XSLT,并将所有测试用例转储出来,忽略它们所属的测试用例块。

在尝试之前不要担心性能。 JAva中的XML API比2003年好得多。

这是您需要的样式表:

<?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>

    <xsl:template match="/">
            <TestCaseBlock>
                <xsl:apply-templates/>
            </TestCaseBlock>
    </xsl:template>

    <xsl:template match="//TestCase">
          <xsl:copy-of select="."/> 
    </xsl:template>

</xsl:stylesheet>

经测试,它有效。

顺便说一句,这个XSLT是在1ms内在这个(小)的例子中编译和执行的。

答案 2 :(得分:1)

如果结构足够常规以便您可以使用数据绑定,我实际上会考虑使用JAXB将两个文件中的XML绑定到对象中,然后合并对象,将其序列化为XML。 如果文件大小很大,你也可以绑定子树;为此,您使用XMLStreamReader(来自Stax api,javax.xml.stream)迭代到作为根的元素,将该元素(及其子元素)绑定到您想要的对象,迭代到下一个根元素。

答案 3 :(得分:0)

我认为XSLT和SAX可以成为一种解决方案。

如果您使用Stream,STaX是解决方案,我阅读Sun教程,我认为非常有帮助: Sun Tutorail on STaX

再见

答案 4 :(得分:0)

检查XmlCombiner这是一个以这种方式实现XML合并的Java库。它基于plexus-utils库提供的类似功能。

在您的情况下,标签也应根据属性&#39; TestCaseID&#39;的值进行匹配。以下是完整的示例:

import org.atteo.xmlcombiner.XmlCombiner;

// create combiner
XmlCombiner combiner = new XmlCombiner("TestCaseID");
// combine files
combiner.combine(firstFile);
combiner.combine(secondFile);
// store the result
combiner.buildDocument(resultFile);

免责声明:我是图书馆的作者。

答案 5 :(得分:0)

您可以将XML视为文本文件并将其组合。与其他方法相比,这非常快。请看下面的代码:-

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class XmlComb {

    static Set<String> lstheader = new HashSet<String>();

    public static void main(String[] args) throws IOException {
        Map<String,List<String>> map1 = getMapXml("J:\\Users\\Documents\\XMLCombiner01\\src\\main\\resources\\File1.xml");
        Map<String,List<String>> map2 = getMapXml("J:\\Users\\Documents\\XMLCombiner01\\src\\main\\resources\\File2.xml");
        Map<String,List<String>> mapCombined = combineXML(map1, map2);

        lstheader.forEach( lst -> {
            System.out.println(lst);
        });

        try {
            mapCombined.forEach((k,v) -> {

                System.out.println(k);
                v.forEach(val -> System.out.println(val));


            });
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static Map<String,List<String>> combineXML(Map<String, List<String>> map1, Map<String, List<String>> map2 ) {

        Map<String,List<String>> map2Modified = new TreeMap<String, List<String>>();
        Map<String,List<String>> mapCombined = new TreeMap<String, List<String>>();
        // --- Modifying map ---
            for(String strKey2 : map2.keySet()) {

                if(map1.containsKey(strKey2)) {
                    map2Modified.put(strKey2.split("\">")[0] + "_1\">", map2.get(strKey2));
                }
                else {
                    map2Modified.put(strKey2 , map2.get(strKey2));
                }
            }   

            //---- Combining map ---

            map1.putAll(map2Modified);

            return map1;
    }


     public static Map<String,List<String>> getMapXml(String strFilePath) throws IOException{
         File file = new File(strFilePath);

        BufferedReader br = new BufferedReader(new FileReader(file));
        Map<String, List<String>> testMap = new TreeMap<String, List<String>>();
        List<String> lst = null;

        String st;
        String strCatalogName = null;
        while ((st = br.readLine()) != null) {
            //System.out.println(st);
            if(st.toString().contains("<TestCase")){
                lst = new ArrayList<String>();
                strCatalogName = st;
                testMap.put(strCatalogName, lst);
            }
            else if(st.contains("</TestCase")){
                lst.add(st);
                testMap.put(strCatalogName,lst);
            }
            else {
                if(lst != null){
                    lst.add(st);
                }else {
                    lstheader.add(st);
                }

            }

        }

        return testMap;
    }
}