title: XML XPath Parsing in Java
body: <p>This is the following standard code to parse XML using XPath in Java. I am unable to debug why I am getting null values. I have attached the java file, the xml file and the output. Would appreciate if somebody can explain a little where I am going wrong. Thanks in advance! :)</p>
  
  <p>XPathParser.java</p>
  
  <pre><code>import javax.xml.parsers.DocumentBuilder;
  import javax.xml.parsers.DocumentBuilderFactory;
  import javax.xml.xpath.XPath;
  import javax.xml.xpath.XPathConstants;
  import javax.xml.xpath.XPathExpression;
  import javax.xml.xpath.XPathFactory;
  
  import org.w3c.dom.Document;
  import org.w3c.dom.NodeList;
  
  public class XPathParser {
      public static void main(String args[]) throws Exception {
          //loading the XML document from a file
          DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
          builderfactory.setNamespaceAware(true);
  
          //XML read
          DocumentBuilder builder = builderfactory.newDocumentBuilder();
          Document xmlDocument = builder.parse("Stocks.xml");
  
          // Creates a XPath factory
          XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
  
          //Creates a XPath Object
          XPath xPath = factory.newXPath();
  
          //Compiles the XPath expression
          //XPathExpression xPathExpression_count = xPath.compile("count(//stock)");
          XPathExpression xPathExpression = xPath.compile("//stock");
  
          //Run the query and get a nodeset
          Object result = xPathExpression.evaluate(xmlDocument,XPathConstants.NODESET);
  
          //Cast the result into a DOM nodelist
          NodeList nodes = (NodeList) result;
          System.out.println(nodes.getLength());
          System.out.println(nodes.item(0));
          for (int i=0; i&lt;nodes.getLength();i++){
            System.out.println(nodes.item(i).getNodeValue());
          }
      }
  }
  </code></pre>
  
  <p>Stocks.xml</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;stocks&gt;
         &lt;stock&gt;
                &lt;symbol&gt;ABC&lt;/symbol&gt;
                &lt;price&gt;10&lt;/price&gt;
                &lt;quantity&gt;50&lt;/quantity&gt;
         &lt;/stock&gt;
         &lt;stock&gt;
                &lt;symbol&gt;XYZ&lt;/symbol&gt;
                &lt;price&gt;20&lt;/price&gt;
                &lt;quantity&gt;1000&lt;/quantity&gt;
         &lt;/stock&gt;
  &lt;/stocks&gt;
  </code></pre>
  
  <p>OUTPUT:</p>
  
  <pre><code>2
  [stock: null]
  null
  null
  </code></pre>