Always get null when querying XML using XPath

I use the following code to query some XML with XPath, which I get from the stream.

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(false); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(inputStream); inputStream.close(); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//FOO_ELEMENT"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); 

I checked the stream for the content, converting it to a string - and it's all there - so it is not as if there was no data in the stream.

It just annoys me now - since I tried different bits of code, and I still keep typing "zero" on the line "System.out.println" - what am I missing here?

NOTE. I want to see the text inside the element.

+4
source share
2 answers

In addition to what Brabster suggested, you can try

 System.out.println(nodes.item(i).getTextContent()); 

or

 System.out.println(nodes.item(i).getNodeName()); 

depending on what you are going to display.

See http://java.sun.com/javase/6/docs/api/org/w3c/dom/Node.html

+7
source

Not an expert in Java XPath impl tbh, but it might help.

javadocs say the result of getNodeValue () will be null for most node types.

It is not entirely clear what you expect to see at the exit; element name, attributes, text? I guess the text. In any XPath impl that I used, if you want the textual content of a node, you should use XPath to

 //FOO_ELEMENT/text() 

Then the value of node is the text content of node.

The getTextContent () method will return the text content of the node that you selected using XPath and any descendant nodes, according to javadoc. The above solution accurately selects the text component of any FOO_ELEMENT nodes in the document.

Java EE Docs for Node <- old documents, see comments on current documents.

+4
source

All Articles