【问题标题】:XPathExpression not evaluatng in the proper context?XPathExpression 不在适当的上下文中进行评估?
【发布时间】:2011-05-13 18:10:45
【问题描述】:

我正在尝试解析来自 USGS 的一些 XML。

Here's an example

“parameterCd”参数列出了我要返回的 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();
}

【问题讨论】:

    标签: java android xpath evaluate


    【解决方案1】:

    尝试改变

    //ns1:variable
    

    .//ns1:variable
    

    尽管正如文档所说,表达式是在当前节点的上下文中评估的,// 是特殊的并且(除非修改)总是意味着“从根目录搜索整个文档'。通过将. 放入其中,您可以强制表达您想要的意思,“从该点向下搜索整棵树”。

    【讨论】:

    • 为什么它可以使用起始点而不是没有起始点?
    • 编辑帮助。然而,从我的角度来看,我发现“从根目录搜索整个文档”的强制规则非常奇怪
    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    相关资源
    最近更新 更多