0

我有几个 xml 需要与不同的相似 xml 集进行比较,并且在比较时我需要根据条件忽略标签,例如

  1. personal.xml - 忽略全名
  2. address.xml - igone 邮政编码
  3. contact.xml - 忽略家庭电话

这是代码

            Diff documentDiff=DiffBuilder
                    .compare(actualxmlfile)
                    .withTest(expectedxmlfile)
                    .withNodeFilter(node -> !node.getNodeName().equals("FullName"))                     
                    .ignoreWhitespace()
                    .build();

我如何在“ .withNodeFilter(node -> !node.getNodeName().equals("FullName")) ”处添加条件,或者有更聪明的方法来做到这一点

4

2 回答 2

0

您可以使用 "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具有不同过滤器的单独对象。这可能会导致更清晰的代码。

于 2020-11-20T17:26:45.110 回答
0

我在下面的链接中为!node.getNodeName().equals("FullName")(您在代码中使用)提供了单独的方法,我认为通过使用该单独的方法,您可以传递节点数组您想忽略并查看结果。如果您希望根据您的要求添加任何其他条件,您可以尝试使用此方法进行游戏。

https://stackoverflow.com/a/68099435/13451711

于 2021-06-23T14:50:02.517 回答