title: JDOM, XPath and Namespace Interactions
body: <p>I'm having a very frustrating time extracting some elements from a JDOM document using an XPath expression. Here's a sample XML document - I'd like to remove the ItemCost elements from the document altogether, but I'm having trouble getting an XPath expression to evaluate to anything at the moment. </p>
  
  <pre><code>  &lt;srv:getPricebookByCompanyResponse xmlns:srv="http://ess.com/ws/srv"&gt;
       &lt;srv:Pricebook&gt;
          &lt;srv:PricebookName&gt;Demo Operator Pricebook&lt;/srv:PricebookName&gt;
          &lt;srv:PricebookItems&gt;
             &lt;srv:PricebookItem&gt;
                &lt;srv:ItemName&gt;Demo Wifi&lt;/srv:ItemName&gt;
                &lt;srv:ProductCode&gt;DemoWifi&lt;/srv:ProductCode&gt;
                &lt;srv:ItemPrice&gt;15&lt;/srv:ItemPrice&gt;
                &lt;srv:ItemCost&gt;10&lt;/srv:ItemCost&gt;
             &lt;/srv:PricebookItem&gt;
             &lt;srv:PricebookItem&gt;
                &lt;srv:ItemName&gt;1Mb DIA&lt;/srv:ItemName&gt;
                &lt;srv:ProductCode&gt;Demo1MbDIA&lt;/srv:ProductCode&gt;
                &lt;srv:ItemPrice&gt;20&lt;/srv:ItemPrice&gt;
                &lt;srv:ItemCost&gt;15&lt;/srv:ItemCost&gt;
             &lt;/srv:PricebookItem&gt;
          &lt;/srv:PricebookItems&gt;
       &lt;/srv:Pricebook&gt;
    &lt;/srv:getPricebookByCompanyResponse&gt;
  </code></pre>
  
  <p>I would normally just use an expression such as //srv:ItemCost to identify these elements, which works fine on other documents, however here it continually returns 0 nodes in the List. Here's the code I've been using:</p>
  
  <pre><code>Namespace ns = Namespace.getNamespace("srv","http://ess.com/ws/srv");   
  XPath filterXpression = XPath.newInstance("//ItemCost");
  filterXpression.addNamespace(ns);   
  List nodes = filterXpression.selectNodes(response);
  </code></pre>
  
  <p>Where response is a JDOM element containing the above XML snippet (verified with an XMLOutputter). nodes continually has size()==0 whenever parsing this document. Using the XPath parser in Eclipse on the same document, this expression does not work either. After some digging, I got the Eclipse evaluator to work with the following expression: //*[local-name() = 'ItemCost'], however replacing the //srv:ItemCost in the Java code with this still produced no results. Another thing I noticed is if I remove the namespace declaration from the XML, //srv:ItemCost will resolve correctly in the Eclipse parser, but I can't remove it from the XML. I've been scratching my head for ours hours on this one now, and would really appreciate some nudging in the right direction. </p>
  
  <p>Many thanks</p>
  
  <p>Edit : Fixed code - </p>
  
  <pre><code>Document build = new Document(response);
  XPath filterXpression = XPath.newInstance("//srv:ItemCost");
  List nodes = filterXpression.selectNodes(build);
  </code></pre>