XPathExpression not being evaluated in the proper context?

I am trying to parse some XML from USGS.

Here is an example

The parameterCd parameter lists 3 data items that I want to return. I can or cannot return all 3.

I am doing this on Android using javax libraries.

In my code, I initially retrieve the 0-3 ns1: timeSeries nodes. It works great. What I want to do then is that in the context of one timeSeries node, the nodes ns1: variable and ns1: values ​​are retrieved.

So, in my code below, where I have:

expr = xpath.compile("//ns1:variable");
NodeList variableNodes = (NodeList) expr.evaluate(timeSeriesNode, XPathConstants.NODESET);

I would expect to get only one node, since the evaluation MUST occur in the context of the only timeSeriesNode that I pass (as per the documentation ). Instead, however, it returns all the ns1 nodes: variables for the document.

Did I miss something?

Here are the relevant parts ...

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();
}
+5
source share
1 answer

Try to change

//ns1:variable

to

.//ns1:variable

Despite the fact that, as the documents say, the expression is evaluated in the context of the current node, //is special and (if it is not changed) always means "search for the entire document from the root". By putting .in, you force the value you want to "find the whole tree from this point down."

+5
source

All Articles