[英]Retrieve particular child node using xpath in java
我有像下面这样的 xml
<results>
<result>
<location>/tmp/path1</location>
<name>name1</name>
</result>
<result>
<location>/tmp/path2</location>
<name>name2</name>
</result>
</results>
我想遍历所有结果对象并使用每个对象的location
和name
。 我正在使用以下代码来获取结果对象列表
XPathExpression expression = XPathFactory.newInstance().newXPath().compile("/results/result");
NodeList nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
// ??
}
如何从节点获取location
和name
值?
您可以像这样获取值。 还有其他的可能性。 虽然我没有优化代码。
XPathExpression expression = XPathFactory.newInstance().newXPath().compile("/results/result");
NodeList nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
String location = XPathFactory.newInstance().newXPath().evaluate("location", DomSource(node));
String name = XPathFactory.newInstance().newXPath().evaluate("name", new DomSource(node));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.