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 ("").

Wayne
  • 59,728
  • 15
  • 131
  • 126
AdrianS
  • 1,980
  • 7
  • 33
  • 51
  • I'm no XPath expert, but don't you address attributes with `@attribute` only? You have `/@path`. Try `/application/resources/resource@path`. – Thomas Dec 30 '11 at 13:58
  • 2
    /application/resources/resource/@path is correct way to address attribute – RanRag Dec 30 '11 at 14:05

1 Answers1

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");
kan
  • 28,279
  • 7
  • 71
  • 101
  • You mean to say that the nodes are not in *no* namespace. They *are* in the *default* namespace. – Wayne Jan 03 '12 at 20:37