Java XPath query does not get text in node?

kosmos

New Member
When I run the following code, I get the output \[code\]Left:\[/code\] instead of \[code\]Left: 16\[/code\].\[code\] // 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(); }\[/code\]Here is the XML file\[code\]<settings> <boundaries> <left>16</left> <right>301</right> <bottom>370</bottom> <top>171</top> </boundaries></settings>\[/code\]EDIT: Based on the answers, this should work, but it doesn't:\[code\]// 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(); }\[/code\]Also note that this code,\[code\]Element el = (Element) dom.getDocumentElement() .getElementsByTagName("boundaries").item(0);System.out.println(el.getElementsByTagName("left").item(0));\[/code\]Prints \[code\][left: null]\[/code\]
 
Back
Top