Search code examples
javaxmlunitxmlunit-2

Can't register namespace with XMLUnit


I can't seem to work out how to set namespace when comparing XML's using xmlunit-2

Tried like:

   @Test
    public void testDiff_withIgnoreWhitespaces_shouldSucceed() {
        // prepare testData
        String controlXml = "<a><text:b>Test Value</text:b></a>";
        String testXml = "<a>\n <text:b>\n  Test Value\n </text:b>\n</a>";
        Map<String, String> namespaces = new HashMap<String, String>();
        namespaces.put("text","urn:oasis:names:tc:opendocument:xmlns:text:1.0");
        // run test
        Diff myDiff = DiffBuilder.compare(Input.fromString(controlXml).build())
                      .withTest(Input.fromString(testXml).build())
                      .withNamespaceContext(namespaces)
                      .ignoreWhitespace()
                      .build();

        // validate result
        Assert.assertFalse("XML similar " + myDiff.toString(), myDiff.hasDifferences());

    }

but always get

org.xmlunit.XMLUnitException: The prefix "text" for element "text:b" is not bound.

stripping away the namespace prefix from elements make it work, but I would like to learn how register properly the namespace with DiffBuilder.

The same problem/ignorence I experience with xmlunit-1.x so hints using that library I would appreciate as well.

EDIT, based on the answer

By adding the namespace attribute to the root node I managed to bind the namespace

<a xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">

thanks Stefan


Solution

  • NamespaceContext is only used for the XPath associated with the "targets" of comparisions. It is not intended to be used to provide mappings for the XML documents you compare.

    There is no way of binding XML namespaces to prefixes outside of the documents themselves in XMLUnit. This means you either must use xmlns attributes or not use prefixes at all.