Search code examples
javaxmlxpathxsi

XPath returns null when I remove the prefix


I am using XPath in Java under Eclipse. I am writing a soap web service, the XML is using prefix and a namespace and I wanted to remove the prefix and only keep the namespace because I prefer a more readable looking XML document.

When I removed the prefixes from XML definition file and tried to query the XML with XPath I started to get null for every node in the XML!

My question is do I have to use a prefix if I want to use XPath? isn't just namespace is enough?

<myrequest
    xmlns="http://www.mywebsite.com/xml/webservice"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.mywebsite.com/xml/webservice Request.xsd">

   <state>     
       <value>demox</value>

this is how my XML starts and when I query this with XPath like XPath.selectSingleNode() I always receive null from the XPath for every node in it.

String myExpression = "myrequest/state/value";  
Document doc = new Document(requestXML);    
Element e = doc.getRootElement();
request.setMybase(getBase((org.jdom.Element) 
            XPath.selectSingleNode(doc,myExpression)));

Solution

  • With XPath 1.0 to select elements in a namespace you need to use a prefix in your XPath expression to qualify element names. So even with the XML being cleaned up to not use a prefix but rather a default namespace declaration in your XPath expression you need to use a prefix bound to the default namespace you have (http://www.mywebsite.com/xml/webservice). How you bind a prefix to a namespace URI depends on the XPath API you use, I am not familiar with JDOM, check its API yourself on how to bind prefixes to namespace URIs.

    [edit]The method is http://www.jdom.org/docs/apidocs/org/jdom/xpath/XPath.html#addNamespace%28java.lang.String,%20java.lang.String%29. so choose any prefix you like (e.g. "pf") and do addNamespace("pf", "http://www.mywebsite.com/xml/webservice"), then use that prefix in your XPath (e.g. "pf:myrequest/pf:state/pf:value").