使用 Java 中的 XPath 提取 XML 中的节点值
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 文档的这些节点值?
我提到了 this 但我的 xpath 如上所示,即它没有 *
或 text()
格式。
xpath evaluator 非常适合我的输入格式,那么有什么方法可以在 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
我有一个 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 文档的这些节点值?
我提到了 this 但我的 xpath 如上所示,即它没有 *
或 text()
格式。
xpath evaluator 非常适合我的输入格式,那么有什么方法可以在 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