Search code examples
xmlunit-2

XMLUnit NodeFilter not finding difference


Comparing two simple XMLs and want to compare nodes with specific localName. In this case only flowerA. When i use not equals to flowerB it gives me the difference for flowerA node, when i say equals to flowerA it doesnt give any difference?

    public class XMLDiff {
        public static void main(String[] args) {
            String controlXml = "<flowers><flowerA>Rose</flowerA><flowerB>Daisy</flowerB></flowers>";
            String testXml =    "<flowers><flowerA>Roses</flowerA><flowerB>Daisies</flowerB></flowers>";

            Diff build = DiffBuilder.compare(controlXml).withTest(testXml)
                    .ignoreWhitespace()
                    .withNodeFilter(node -> !node.getNodeName().equals("flowerB"))
                    .build();
            System.out.println(build.getDifferences());
        }
    }
[Expected text value 'Rose' but was 'Roses' - comparing <flowerA ...>Rose</flowerA> at /flowers[1]/flowerA[1]/text()[1] to <flowerA ...>Roses</flowerA> at /flowers[1]/flowerA[1]/text()[1] (DIFFERENT)]
    public class XMLDiff {
        public static void main(String[] args) {
            String controlXml = "<flowers><flowerA>Rose</flowerA><flowerB>Daisy</flowerB></flowers>";
            String testXml =    "<flowers><flowerA>Roses</flowerA><flowerB>Daisies</flowerB></flowers>";

            Diff build = DiffBuilder.compare(controlXml).withTest(testXml)
                    .ignoreWhitespace()
                    .withNodeFilter(node -> node.getNodeName().equals("flowerA"))
                    .build();
            System.out.println(build.getDifferences());
        }
    }
[]

Solution

  • Your root element flowers is not matched by the NodeFilter and so you end up with comparing nothing at all.

    NodeFilter is best suited for a deny list of nodes you do not want to compare. In your case you need to ensure you also allow all nodes that are encountered while traversing to the node you are interested in.