2

I have the following XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application xmlns="http://research.sun.com/wadl/2006/10">
<doc xmlns:jersey="http://jersey.dev.java.net/" 
     jersey:generatedBy="Jersey: 1.0.2 02/11/2009 07:45 PM"/>
<resources base="http://localhost:8080/stock/">
    <resource path="categories"> (<<---I want to get here)
        <method id="getCategoriesResource" name="GET">

And I want to get the value of resource/@path so I have the following Java code:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = factory.newDocumentBuilder();
// get the xml to parse from URI
Document doc = builder.parse(serviceUri + "application.wadl"); 
XPathFactory xfactory = XPathFactory.newInstance();
XPath xpath = xfactory.newXPath();
XPathExpression expression = 
        xpath.compile("/application/resources/resource/@path");
this.baseUri = (String) expression.evaluate(doc, XPathConstants.STRING);

With this XPath expression the result (baseUri) is always the empty string ("").

2
  • I'm no XPath expert, but don't you address attributes with @attribute only? You have /@path. Try /application/resources/resource@path. Commented Dec 30, 2011 at 13:58
  • 2
    /application/resources/resource/@path is correct way to address attribute Commented Dec 30, 2011 at 14:05

1 Answer 1

5

The nodes are not in the empty string namespace, you must specify it: /wadl:application/wadl:resources/wadl:resource/@path. Also, you should register the namespace in the XPath engine namespace context.

This is working example:

    xpath.setNamespaceContext(new NamespaceContext()
    {
        @Override
        public String getNamespaceURI(final String prefix)
        {
            if(prefix.equals("wadl"))
                return "http://research.sun.com/wadl/2006/10";
            else
                return null;
        }

        @Override
        public String getPrefix(final String namespaceURI)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public Iterator getPrefixes(final String namespaceURI)
        {
            throw new UnsupportedOperationException();
        }
    });
    XPathExpression expression = xpath.compile("/wadl:application/wadl:resources/wadl:resource/@path");
Sign up to request clarification or add additional context in comments.

1 Comment

You mean to say that the nodes are not in no namespace. They are in the default namespace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.