当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Always get null when querying XML with 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.

网友答案:

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

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: