1
我有一个如下所示的XML文件。在使用xmlUnit进行比较时忽略多个标签
预期的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标签<file>
下面是我写的
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文件有一个以上的<tag>...</tag>
块不工作比较代码。基本上,我需要在这里正则表达式而忽略所有<file>
标签,它正在<doc><tag>
我想预期和测试XML的比较表明,无论是忽略文件变量的值相同,所以diff.similar()
应该返回true
请建议如何去做。
这将是更容易理解你的目标,如果你比你的文件结构中增加了预期的结果。 –
我找到了解决方案。 ignoresXPathsRegex .add(“\\/doc \\ [1 \\] \\/tag \\ [1 \\] \\/file \\ [1 \\] \\/text()”);告诉只检查第一个标签。我们应该使用ignorableXPathsRegex .add(“\\/doc \\ [1 \\] \\/tag \\ [\\ d * \\] \\/file \\ [1 \\] \\/text( )“);忽略所有里面的所有 –
user3540481