Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPathExpression not evaluatng in the proper context?

I'm trying to parse some XML from the USGS.

Here's an example

The "parameterCd" parameter lists the 3 items of data I want back. I may or may not get all 3 back.

I'm doing this on an Android using the javax libraries.

In my code, I initially retrieve the 0-3 ns1:timeSeries nodes. This works fine. What I then want to do is, within the context of a single timeSeries node, retrieve the ns1:variable and ns1:values nodes.

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 only get back one node, since the evaluate SHOULD be happening in the context of the single timeSeriesNode that I'm passing in (according to the documentation). Instead, however, it returns all of the ns1:variable nodes for the document, however.

Am I missing something?

Here's the relevant portions...

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();
}
like image 889
Pete Avatar asked May 13 '11 18:05

Pete


1 Answers

Try changing

//ns1:variable

to

.//ns1:variable

Even though, as the docs say, the expression is evaluated within the context of the current node, // is special and (unless modified) always means 'search the whole document from the root'. By putting the . in, you force the meaning you want, 'search the whole tree from this point downwards'.

like image 83
AakashM Avatar answered Nov 12 '22 18:11

AakashM