我正在尝试从 USGS 解析一些 XML。
“parameterCd”参数列出了我要返回的 3 项数据。我可能会也可能不会全部 3 回来。
我正在使用 javax 库在 Android 上执行此操作。
在我的代码中,我最初检索 0-3 ns1:timeSeries 节点。这很好用。然后我想做的是,在单个 timeSeries 节点的上下文中,检索 ns1:variable 和 ns1:values 节点。
所以在我下面的代码中我有:
expr = xpath.compile("//ns1:variable");
NodeList variableNodes = (NodeList) expr.evaluate(timeSeriesNode, XPathConstants.NODESET);
我希望只取回一个节点,因为评估应该发生在我传入的单个 timeSeriesNode 的上下文中(根据 documentation )。但是,它会返回文档的所有 ns1:variable 节点。
我错过了什么吗?
这里是相关部分...
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
xpath.setNamespaceContext(new InstantaneousValuesNamespaceContext());
XPathExpression expr;
NodeList timeSeriesNodes = null;
InputStream is = new ByteArrayInputStream(sourceXml.getBytes());
try {
expr = xpath.compile("//ns1:timeSeries");
timeSeriesNodes = (NodeList) expr.evaluate(new InputSource(is), XPathConstants.NODESET);
for(int timeSeriesIndex = 0;timeSeriesIndex < timeSeriesNodes.getLength(); timeSeriesIndex++){
Node timeSeriesNode = timeSeriesNodes.item(timeSeriesIndex);
expr = xpath.compile("//ns1:variable");
NodeList variableNodes = (NodeList) expr.evaluate(timeSeriesNode, XPathConstants.NODESET);
// Problem here. I've got all the variables, not the individual one I want.
for(int variableIndex = 0; variableIndex < variableNodes.getLength(); variableIndex++){
Node variableNode = variableNodes.item(variableIndex);
expr = xpath.compile("//ns1:valueType");
NodeList valueTypeNodes = (NodeList) expr.evaluate(variableNode, XPathConstants.NODESET);
}
}
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
最佳答案
尝试改变
//ns1:variable
到
.//ns1:variable
尽管如文档所说,表达式是在当前节点的上下文中计算的,//
是特殊的并且(除非修改)始终 表示“搜索整个文件从根'。通过放入 .
,您可以强加您想要的意思,“从这一点向下搜索整棵树”。
关于java - XPathExpression 没有在适当的上下文中评估?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5996029/