getNodeValue()在java中返回null
我试图通过计算getNodeValue()在java中返回null,java,dom,xpath,xml-parsing,Java,Dom,Xpath,Xml Parsing,我试图通过计算xpath表达式来找到节点值 String resp="<response><result><phone>1234</phone><sys_id>dfcgf34dfg56</sys_id></result></response>"; DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); Do
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());
String resp=“1234DFCFGF34DFG56”;
DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder=domFactory.newDocumentBuilder();
org.w3c.dom.Document dDoc=builder.parse(新的InputSource(新的ByteArrayInputStream(resp.getBytes(“utf-8”)));
XPath=XPathFactory.newInstance().newXPath();
Node Node=(Node)xPath.evaluate(“//response/result/sys\u id”,dDoc,XPathConstants.Node);
System.out.println(node.getNodeName()+”,“+node.getNodeValue());
当系统id明显不为空时,这会给出输出:sys\u id,null
返回正确的值
有人能指出错误吗
谢谢大家! 我不是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();
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);
代码中有一个输入错误:在解析输入时,使用了一个名为“resp”的变量,但定义了一个名为“resp1”的变量 显示输入错误:为了捕获文本内容,请使用node.getTextContent()
代码返回null的原因是:您正在提取一个元素节点,getNodeValue()的结果取决于节点类型(请参见中的表),并且对于元素节点总是返回null。您的代码看起来正常,但调试它时,
dDoc
总是为null,因此sys\u id
将为null…这是有效的,非常感谢。关于这一点,如果xml字符串由许多标记组成,我们如何获取所有记录的sys\u id字段?请尝试使用以下命令:/response/result/sys\u id/text()。。。这应该返回所有的sys\u id
节点,您可以从中提取内容。我最初也看到了这个输入错误,但他纠正了它,所以我认为问题出在其他地方。是的,问题是对getNodeValue()的调用,该调用对于元素节点总是返回null
dfcgf34dfg56
System.out.println(node +": " + node.getNodeName() + ", " + node.getTextContent());