【问题标题】:Ignore a multiple occurrence of a tag while comparing using xmlUnit使用 xmlUnit 进行比较时忽略标签的多次出现
【发布时间】:2015-07-22 05:47:32
【问题描述】:

我有一个如下所示的 XML 文件。

预期的 XML

<doc>
<tag>
    <file>a.c</file>
    <line>10</line>
    <type>c</type>
<tag>
<tag>
    <file>b.h</file>
    <line>14</line>
    <type>h</type>
<tag>
<tag>
    <file>d.he</file>
    <line>49</line>
    <type>he</type>
<tag>
</doc>

现在用 XML 进行测试

<doc>
<tag>
    <file>a1.c</file>
    <line>10</line>
    <type>c</type>
<tag>
<tag>
    <file>b1.h</file>
    <line>14</line>
    <type>h</type>
<tag>
<tag>
    <file>d1.he</file>
    <line>49</line>
    <type>he</type>
<tag>
</doc>

我想将此文件与另一个具有相同结构的 XML 文件进行比较。

我正在使用 xmlUnit 进行比较。比较时我想忽略 XML 标记 &lt;file&gt;

下面是我写的对比代码

public static Diff compareXML(String expXMLPath, String genXMLPath)
        throws IOException, SAXException {
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreAttributeOrder(true);
    final List<String> ignorableXPathsRegex = new ArrayList<String>();// list of regular expressions that custom difference listener used during xml 
    //comparison                                                                                
    ignorableXPathsRegex
            .add("\\/doc\\[1\\]\\/tag\\[1\\]\\/file\\[1\\]\\/text()");        
    Diff diff = null;
    try(FileInputStream fileStream1 = new FileInputStream(expXMLPath)) {
        try(FileInputStream fileStream2 = new FileInputStream(genXMLPath)) {
            InputSource inputSource1 = new InputSource(fileStream1);
            InputSource inputSource2 = new InputSource(fileStream2);
            diff = new Diff(inputSource1, inputSource2);
            RegDiffListener ignorableElementsListener = new RegDiffListener(
                    ignorableXPathsRegex);
            diff.overrideDifferenceListener(ignorableElementsListener);
            return diff;
        }
    }                
}

如果 XML 文件有多个 &lt;tag&gt;...&lt;/tag&gt; 块,这将不起作用。我基本上需要一个正则表达式,它忽略&lt;doc&gt;&lt;tag&gt;下的所有&lt;file&gt;标签

我希望通过忽略文件标签的值来比较预期和测试 XML 以显示两者相同,因此 diff.similar() 应该返回 true

请建议如何做。

【问题讨论】:

  • 与文件结构相比,添加预期结果会更容易理解您的目标。
  • 我找到了解决方案。 ignorableXPathsRegex .add("\\/doc\[1\]\\/tag\[1\]\\/file\[1\]\\/text()");告诉只检查第一个标签。我们应该使用 ignorableXPathsRegex .add("\\/doc\[1\]\\/tag\[\\d*\]\\/file\[1\]\\/text()");忽略所有 中的所有

标签: regex xml xmlunit


【解决方案1】:

我找到了解决办法。

ignorableXPathsRegex .add("\\/doc\[1\]\\/tag\[1\]\\/file\[1\]\\/text()");

告诉只检查第一个标签。

我们应该使用

ignorableXPathsRegex .add("\\/doc\[1\]\\/tag\[\\d+\]\\/file\[1\]\\/text()");

忽略所有&lt;tag&gt;中的所有&lt;file&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 2020-07-21
    • 1970-01-01
    • 2018-11-26
    • 2018-08-16
    • 1970-01-01
    相关资源
    最近更新 更多