Search code examples
javaxmlxmlunit

XMLUNIT ignore xmlns?


Try to get this two XML like similar (want to ignore xmlns) and differer element sequance but not working correctly for me. If remove xmlns, doc are simmilr. I am Using XMlUnit 1.5

String s1 = "<root xmlns=\"http:example.com\">"
                        +"<Date/>"
                        +"<Time/>"
                     +"</root>";

String s2 = "<root>"
                      +"<Time/>"
                      +"<Date/>"
                   +"</root>";
myDiff = XMLUnit.compareXML(s1,s2);

Solution

  • There are two things you need to do:

    • in order to ignore the different namespaces you need to provide a DifferenceListener that downgrades the difference
    • the default ElementQualifier used by Diff is ElementNameQualifier that only compares elements with the same local name and namespace URI. You need to override this one as well.

      Diff xmlDiff = new Diff(s1, s2);
      xmlDiff.overrideElementQualifier(new ElementNameQualifier() {
              @Override
              protected boolean equalsNamespace(Node control, Node test) {
                  return true;
              }
          });
      xmlDiff.overrideDifferenceListener(new DifferenceListener() {
              @Override
              public int differenceFound(Difference diff) {
                  if (diff.getId() == DifferenceConstants.NAMESPACE_URI_ID) {
                      return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
                  }
                  return RETURN_ACCEPT_DIFFERENCE;
              }
              @Override
              public void skippedComparison(Node arg0, Node arg1) { }
          });
      

    creates a "similar" result. In order get an "identical" result you'd also need to downgrade CHILD_NODELIST_SEQUENCE_ID differences.