Java XPath query does not get text in node?

java, xml, xpath

Solution

The nodes are indexed starting at 1. Try `/settings/boundaries[1]/left[1]`

Problem

When I run the following code, I get the output `Left:` instead of `Left: 16`. ``` // Retrieve DOM from XML file DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; Document dom = null; try { db = dbf.newDocumentBuilder(); dom = db.parse("config"); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); try { String left = (String) xPath.evaluate( "/settings/boundaries[0]/left[0]", dom, XPathConstants.STRING); System.out.println("Left: " + left); } catch (XPathExpressionException e) { // TODO Auto-generated catch block e.printStackTrace(); } ``` Here is the XML file ``` <settings> <boundaries> <left>16</left> <right>301</right> <bottom>370</bottom> <top>171</top> </boundaries> </settings> ``` EDIT: Based on the answers, this should work, but it doesn't: ``` // Retrieve DOM from XML file DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; Document dom = null; try { db = dbf.newDocumentBuilder(); dom = db.parse("config"); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); try { String left = (String) xPath.evaluate( "/settings/boundaries[0]/left[0]/text()", dom, XPathConstants.STRING); System.out.println("Left: " + left); } catch (XPathExpressionException e) { e.printStackTrace(); } ``` Also note that this code, ``` Element el = (Element) dom.getDocumentElement() .getElementsByTagName("boundaries").item(0); System.out.println(el.getElementsByTagName("left").item(0)); ``` Prints `[left: null]`

Original source