0

我有两个 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>";

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

姓名:贾杰辛

年龄:31 31

出生日期:1990 年 3 月 28 日 1990 年 3 月 28 日

我的问题:解决这个问题的最简单方法是什么?

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

4

2 回答 2

0

当然,如果您想比较两个 XML,您有一个 XML 单元,您可以逐个字符地进行比较。 XML 单元

编辑:

您必须从这里XML Sourceforge下载 de XMLUnit JAR ,然后像 JUnit 一样简单地将其添加到您的类路径(通过 Eclipse / NetBeans / 等等...),然后编写一个测试,如 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 的简单方法

于 2013-09-05T07:11:44.583 回答
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
            }
        });
于 2013-09-05T07:44:28.637 回答