1

Is it possible to ignore a few children in elements when comparing XML documents with XMLUnit? I want to ignore any empty text nodes in the element when comparing them.

Best Regards, Keshav

keshav84
  • 2,291
  • 5
  • 25
  • 34
  • 1) override the differenceFound in DifferenceListener but then it ignores the other differences in the element. 2) set the XMLUnit.setIgnoreWhitespace(true). this does not seem to work for compareXML(Document control, Document test) – keshav84 Sep 17 '10 at 05:25
  • See http://stackoverflow.com/questions/1241593/java-how-do-i-ignore-certain-elements-when-comparing-xml – Alex B May 13 '11 at 21:35

1 Answers1

1

You can use this listener:

import org.custommonkey.xmlunit.Difference;
import org.custommonkey.xmlunit.DifferenceConstants;
import org.custommonkey.xmlunit.DifferenceListener;
import org.w3c.dom.Node;

import java.util.HashSet;
import java.util.Set;

public class IgnoreChildrenOfNamedElementsDifferenceListener implements DifferenceListener {
    public IgnoreChildrenOfNamedElementsDifferenceListener() {}

    public int differenceFound(Difference difference) {
        if (difference.getId() == DifferenceConstants.HAS_CHILD_NODES_ID ||
                difference.getId() == DifferenceConstants.CHILD_NODELIST_LENGTH_ID ||
                difference.getId() == DifferenceConstants.CHILD_NODE_NOT_FOUND_ID) {
                return DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
            }
        }    
        return DifferenceListener.RETURN_ACCEPT_DIFFERENCE;
    }

    @Override
    public void skippedComparison(Node control, Node test) {}
}

Then you can use it in following way:

Diff diff = new Diff(expectedDoc, obtainedDoc);
diff.overrideDifferenceListener(new IgnoreChildrenOfNamedElementsDifferenceListener("TestDateTime"));
Michał Rowicki
  • 1,372
  • 1
  • 16
  • 28