Xml解析和比较

时间:2013-09-05 06:38:44

标签: java xmlunit

我有两个Xml: -

String xmlA="<user><name>Jai</name><age>31</age><dob>28March1990</dob></user>";
String xmlB="<user><name>Jai Singh</name><age>31</age><dob>28March1990</dob></user>";

现在解析和比较后,我想在下面显示结果 顺序: -

姓名: Jai JaiSingh

年龄:31 31

dob:28March1990 28March1990

我的问题: 最简单的方法是什么?

我可以在这种情况下使用xmlUnit进行比较吗?

2 个答案:

答案 0 :(得分:0)

当然,如果你想比较两个XML,你就有了一个XML单元,你可以逐个字符地完成它。 XML Unit

编辑:

你必须从这里下载de XMLUnit JAR XML Sourceforge,然后像JUnit一样简单地添加到你的类路径中(通过Eclipse / NetBeans等等......)然后你编写一个Test,就像JUnit一样但是从XMLTestCase扩展,就像这样:

import org.custommonkey.xmlunit.*;
public class XMLTesting extends XMLTestCase {


 public void testForEquality() throws Exception {
        String myControlXML = "<msg><uuid>0x00435A8C</uuid></msg>";
        String myTestXML = "<msg><localId>2376</localId></msg>";
        assertXMLEqual("comparing test xml to control xml", myControlXML, myTestXML);

        assertXMLNotEqual("test xml not similar to control xml", myControlXML, myTestXML);
    }

    public void testIdentical() throws Exception {
        String myControlXML = "<struct><int>3</int><boolean>false</boolean></struct>";
        String myTestXML = "<struct><boolean>false</boolean><int>3</int></struct>";
        Diff myDiff = new Diff(myControlXML, myTestXML);
        assertTrue("pieces of XML are similar " + myDiff, myDiff.similar());
        assertTrue("but are they identical? " + myDiff, myDiff.identical());
    }

    public void testAllDifferences() throws Exception {
        String myControlXML = "<news><item id=\"1\">War</item>"
            + "<item id=\"2\">Plague</item><item id=\"3\">Famine</item></news>";
        String myTestXML = "<news><item id=\"1\">Peace</item>"
            + "<item id=\"2\">Health</item><item id=\"3\">Plenty</item></news>";
        DetailedDiff myDiff = new DetailedDiff(compareXML(myControlXML, myTestXML));
        List allDifferences = myDiff.getAllDifferences();
        assertEquals(myDiff.toString(), 0, allDifferences.size());
    }

所以你可以看到比较两个XML

的简单方法

答案 1 :(得分:0)

使用xmlunit

创建两个xml文档并使用Diff进行比较。 DifferenceEngine接受DifferenceListener。你可以在那里添加你的逻辑。

        Diff diff = new Diff(docx1, docx2);
        DifferenceEngine engine = new DifferenceEngine(diff);

        ElementQualifier qualifier = new RecursiveElementNameAndTextQualifier();
        diff = new Diff(docx1, docx2, engine, qualifier);
        diff.overrideDifferenceListener(new DifferenceListener()
        {
            @Override public int differenceFound(Difference difference)
            {
                // Do some thing here


            }

            @Override public void skippedComparison(Node node, Node node1)
            {
                //no op
            }
        });