1

我有两个 XML

<books><book language="English"><authors><author>Niklaus Wirth</author></authors></book><book language="English"><authors><author>Mark Twain</author></authors></book><book language="English"><authors><author>O.-J. Dahl</author></authors></book></books>


<books><book language="English"><authors><author>Niklaus Wirth</author></authors></book><book language="English"><authors><author>O.-J. Dahl</author></authors></book><book language="English"><authors><author>Mark Twain</author></authors></book></books>

最后两个<author>标签的顺序不同,它们应该是相似的。这是代码

public static void compare() throws FileNotFoundException{
        String sourceXML=convertXMLtoString(source);
        String targetXML=convertXMLtoString(target);
        System.out.println(sourceXML);
        System.out.println(targetXML);
        Diff mydiff=DiffBuilder.compare(sourceXML)
        .withTest(targetXML)
        .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byNameAndText))
        .checkForSimilar()
        //.withNodeMatcher()
        .build();
        Iterable<Difference> differences = mydiff.getDifferences();
        for(Difference d:differences){
            System.out.println(d.toString());
        }
    }

这是输出。

Expected child 'author' but was 'null' - comparing <author...> at /books[1]/book[2]/authors[1]/author[1] to <NULL> (DIFFERENT)
Expected child 'null' but was 'author' - comparing <NULL> to <author...> at /books[1]/book[2]/authors[1]/author[1] (DIFFERENT)
Expected child 'author' but was 'null' - comparing <author...> at /books[1]/book[3]/authors[1]/author[1] to <NULL> (DIFFERENT)
Expected child 'null' but was 'author' - comparing <NULL> to <author...> at /books[1]/book[3]/authors[1]/author[1] (DIFFERENT)

谁能告诉我如何忽略这个?我认为将 NameandText 与 Element 选择器一起使用应该忽略该顺序。谢谢

4

1 回答 1

1

使用byNameAndText您确保您选择了正确的author标签,但这为时已晚,因为 XMLUnit 需要选择正确book的标签才能使您的比较成功。一旦确定了book要比较的元素,它就永远不会在不同的子树中搜索元素。

我不认为author这本书最终能区分这些书,但在没有任何其他提示的情况下,比如

ElementSelectors.conditionalBuilder()
    .whenElementIsNamed("book").thenUse(ElementSelectors.byXPath("./authors/author", ElementSelectors.byNameAndText))
    .elseUse(ElementSelectors.byNameAndText)
    .build();

应该可以工作。

于 2016-08-27T13:58:43.953 回答