6

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

文件1.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> 

文件2.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>

合并的.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>
4

6 回答 6

3

我有一个适合我的解决方案。现在专家,请指教,如果这是要走的路。

谢谢,-尼莱什

    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();
于 2011-04-17T23:52:13.983 回答
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 是在 1 毫秒内在这个(小)示例上编译和执行的。

于 2011-04-15T19:53:25.843 回答
1

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

于 2011-04-16T20:04:13.713 回答
0

我认为 XSLT 和 SAX 可能是一个解决方案。

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

再见

于 2011-04-15T20:00:32.883 回答
0

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

在您的情况下,标签也应根据属性“TestCaseID”的值进行匹配。这是完整的示例:

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

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

于 2014-12-02T23:01:46.207 回答
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;
    }
}
于 2019-10-05T19:16:59.347 回答