在使用xmlunit-2比较XML时,我似乎无法弄清楚如何设置名称空间

尝试像:

   @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());

    }


但总是得到


  org.xmlunit.XMLUnitException:元素“ text:b”的前缀“ text”
  没有约束。


从元素中删除名称空间前缀可以使其正常工作,但是我想学习如何使用DiffBuilder正确注册名称空间。

我在xmlunit-1.x上遇到的同样的问题/无知,所以使用该库的提示我也将不胜感激。

编辑,根据答案

通过将名称空间属性添加到根节点,我设法绑定了名称空间

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

谢谢斯蒂芬

最佳答案

NamespaceContext仅用于与比较的“目标”关联的XPath。它不打算用于为您比较的XML文档提供映射。

在XMLUnit中,无法将XML名称空间绑定到文档本身之外的前缀。这意味着您要么必须使用xmlns属性,要么根本不使用前缀。

10-07 16:58