java - XPathExpression 没有在适当的上下文中评估?

标签 java android xpath evaluate

我正在尝试从 USGS 解析一些 XML。

Here's an example

“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/

相关文章:

java - 从一行中获取特定单词

Android:使用选择器设置 ImageView 的背景颜色

Android WifiManager - 停止扫描

java - 循环中的结果回调(从谷歌驱动器下载多张图片。)

ruby - 从 HTML 中抓取轨道数据?

java - 从远程服务器获取 channel 表文件

JavaFX有没有办法包含PDF文件

java - 在 PHP 中获取 Java Println 输出

ios - 使用 Touchxml 和 xcode 动态创建 Xpath 查询

java - 使用 Child 进行 XML 解析而不是值解析