您可以使用 "and" ( ) 将多个条件连接在一起&&
:
private static void doDemo1(File actual, File expected) {
Diff docDiff = DiffBuilder
.compare(actual)
.withTest(expected)
.withNodeFilter(
node -> !node.getNodeName().equals("FullName")
&& !node.getNodeName().equals("ZipCode")
&& !node.getNodeName().equals("HomePhone")
)
.ignoreWhitespace()
.build();
System.out.println(docDiff.toString());
}
如果要保持构建器整洁,可以将节点过滤器移动到单独的方法:
private static void doDemo2(File actual, File expected) {
Diff docDiff = DiffBuilder
.compare(actual)
.withTest(expected)
.withNodeFilter(node -> testNode(node))
.ignoreWhitespace()
.build();
System.out.println(docDiff.toString());
}
private static boolean testNode(Node node) {
return !node.getNodeName().equals("FullName")
&& !node.getNodeName().equals("ZipCode")
&& !node.getNodeName().equals("HomePhone");
}
这样做的风险是您的元素名称可能出现在不止一种类型的文件中 - 需要从一种类型的文件中过滤该节点,而不是其他任何类型的文件。
在这种情况下,您还需要考虑您正在处理的文件类型。例如,您可以使用文件名(如果它们遵循合适的命名约定)或使用根元素(假设它们不同) - 例如<Personal>
, <Address>
, <Contact>
- 或任何它们,在您的情况下。
但是,如果您需要区分 XML 文件类型,出于这个原因,您最好使用该信息来拥有DiffBuilder
具有不同过滤器的单独对象。这可能会导致更清晰的代码。