[英]Extracting the node values in XML with XPath in Java
我有一个XML文档:
<response>
<result>
<phone>1233</phone>
<sys_id>asweyu4</sys_id>
<link>rft45fgd</link>
<!-- Many more in result -->
</result>
<!-- Many more result nodes -->
</response>
XML结构未知。 我正在从用户获取XPath的属性。
例如,输入是字符串,例如: //response/result/sys_id
, //response/result/phone
如何通过评估XPath获得整个XML文档的这些节点值?
我提到了这个,但是我的xpath如上所示,即它没有*
或text()
格式。
xpath评估程序可以很好地与我的输入格式配合使用,所以有什么办法可以在Java中实现相同的效果?
谢谢!
很难看到您的代码...我只是将其评估为NodeList,然后在结果列表中的每个节点上调用getTextContent()。
String input = "<response><result><phone>1233</phone><sys_id>asweyu4</sys_id><link>rft45fgd</link></result><result><phone>1233</phone><sys_id>another-sysid</sys_id><link>another-link</link></result></response>";
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new ByteArrayInputStream(input.getBytes("UTF-8")));
XPath path = XPathFactory.newInstance().newXPath();
NodeList node = (NodeList) path.compile("//response/result/sys_id").evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < node.getLength(); i++) {
System.out.println(node.item(i).getTextContent());
}
产量
asweyu4
another-sysid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.