【问题标题】:Node.getNodeValue() returns null in javaNode.getNodeValue() 在 java 中返回 null
【发布时间】:2015-11-04 18:04:15
【问题描述】:

我正在尝试通过评估 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 返回正确的值。

谁能指出错误?

谢谢!

【问题讨论】:

  • 你的代码看起来不错,但是调试它,dDoc 总是为空,所以sys_id 将为空......

标签: java dom xpath xml-parsing


【解决方案1】:

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

忽略错字:为了捕捉 TextContent 使用 node.getTextContent()

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

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

【讨论】:

  • 我最初也看到了这个错字,但他更正了它,所以我认为问题出在其他地方。
  • 是的,问题是调用 getNodeValue() 总是为 ELEMENT 节点返回 null
【解决方案2】:

我不是 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

【讨论】:

  • 成功了,谢谢!对此,如果xml字符串包含很多标签,我们如何获取所有记录的sys_id字段呢?
  • 尝试使用这个:/response/result/sys_id/text() ...这应该返回所有sys_id节点,您可以从中提取内容。
猜你喜欢
  • 2012-03-26
  • 1970-01-01
  • 2020-03-27
  • 2015-06-04
  • 2019-08-25
  • 2016-05-28
  • 2016-03-08
  • 2015-12-09
相关资源
最近更新 更多