Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always get null when querying XML with XPath

Tags:

java

xml

xpath

I am using the following code to query some XML with XPath I get from a 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 have checked the stream for content by converting it to a string - and it's all there - so it's not as if there is no data in the stream.

This is just annoying me now - as I have tried various different bits of code and I still keep getting 'null' being printed at the "System.out.println" line - what am I missing here?

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

like image 538
Vidar Avatar asked Dec 23 '22 12:12

Vidar


2 Answers

In addition to what Brabster suggested, you may want to try

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

or

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

depending on what you're intending to display.

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

like image 87
Eddie Avatar answered Jan 01 '23 06:01

Eddie


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

The javadocs say that he result of getNodeValue() will be null for most types of node.

It's not totally clear what you expect to see in the output; element name, attributes, text? I'll guess text. In any XPath impl I have used, if you want the text content of the node, you have to XPath to

//FOO_ELEMENT/text()

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

The getTextContent() method will return the text content of the node you've selected with the XPath, and any descendant nodes, as per the javadoc. The solution above selects exactly the text component of the any nodes FOO_ELEMENT in the document.

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

like image 31
brabster Avatar answered Jan 01 '23 05:01

brabster