Node.getNodeValue()在java中返回null

时间:2015-08-12 08:31:56

标签: java dom xpath xml-parsing

我试图通过评估xpath表达式找到节点值。

String resp="<response><result><phone>1234</phone><sys_id>dfcgf34dfg56</sys_id></result></response>";

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder = domFactory.newDocumentBuilder();
org.w3c.dom.Document dDoc = builder.parse(new InputSource(new ByteArrayInputStream(resp.getBytes("utf-8"))));


XPath xPath = XPathFactory.newInstance().newXPath();
Node node = (Node) xPath.evaluate("//response/result/sys_id", dDoc, XPathConstants.NODE);
System.out.println(node.getNodeName()+" , "+node.getNodeValue());

当sys_id显然不为空时,这会给出输出:sys_id , null

xpath evaluator会返回正确的值。

有人可以指出任何错误吗?

谢谢!

2 个答案:

答案 0 :(得分:3)

我不是XPath的专家,但基于this Stack Overflow article,我能够生成以下能够正常工作的代码:

String resp = "<response><result><phone>1234</phone><sys_id>dfcgf34dfg56</sys_id></result></response>";

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFactory.newDocumentBuilder();
org.w3c.dom.Document dDoc = builder.parse(new InputSource(new ByteArrayInputStream(resp.getBytes("utf-8"))));

XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("//response/result/sys_id");  // these 2 lines
String str = (String) expr.evaluate(dDoc, XPathConstants.STRING);  // are different
System.out.println(str);

<强>输出:

dfcgf34dfg56

答案 1 :(得分:2)

您的代码中存在拼写错误:解析输入时使用名为“resp”的变量,但您定义了一个名为“resp1”的变量。

暂停拼写错误:为了捕获TextContent,请使用 node.getTextContent()

System.out.println(node +": " + node.getNodeName() + ", " + node.getTextContent());

您的代码返回null的原因是:您正在提取ELEMENT节点,getNodeValue()的结果取决于节点类型(请参阅API中的表)并始终返回 null 用于ELEMENT节点。