assertXpathEvaluatesTo and default namespace

Help
Borut
2009-06-04
2013-03-03
  • Borut
    Borut
    2009-06-04

    Hello,

    I want to create a test which checks for atribute value. The XML uses a namespace. The test bellow fails. Why?

        @Test
        public void checkVersion() throws ParserConfigurationException, SAXException, IOException, XpathException {
            String t = "<a xmlns=\&quot;http://www.acme.com\&quot;><b c='cv'>bv</b></a>";
           
            Document d = XMLUnit.buildControlDocument(t);
            HashMap m = new HashMap();
            m.put("", "http://www.acme.com");

            NamespaceContext ctx = new SimpleNamespaceContext(m);
            XpathEngine engine = XMLUnit.newXpathEngine();
            engine.setNamespaceContext(ctx);
           
            XMLAssert.assertXpathEvaluatesTo("bv", "//b", d);
        }

    Thanks for any input,
    Borut

     
  • Stefan Baramov
    Stefan Baramov
    2010-02-23

    Well, if i am not mistake, you need to have something for your prefix. Empty string will not cut it. I would do this:

    m.put("ns1", "http://www.acme.com");
    

    Then, you would need to change you xpath expression:

    XMLAssert.assertXpathEvaluatesTo("bv", "//ns1:b", d);
    

    Or you can rewrite the above to look like this :

    @Test
    public void checkVersion() throws ParserConfigurationException, SAXException, IOException, XpathException {
        String t = "<a xmlns=\"http://www.acme.com\"><b c='cv'>bv</b></a>";
        XMLUnit.getControlDocumentBuilderFactory().setNamespaceAware(false);
        XMLAssert.assertXpathEvaluatesTo("bv", "//b", d);
    }
    

    Note, all credit goes to http://blog.davber.com/2006/09/17/xpath-with-namespaces-in-java/

    - Stefan Baramov

     
  • Stefan Bodewig
    Stefan Bodewig
    2010-03-02

    Thanks, Stefan.  The davber post made me try

    //:b
    

    as XPath expression (note the colon with no prefix) and at least with standard JAXP libs it seems to work as well.

    Your "use any namespace prefix" advice is exactly what I did in the testcase in svn to show that it worked.

    I cannot find any explicit documentation that says you must use namespace prefixes in the XPath expression if your document is using namespaces, but it seems to be true nonetheless.