0

I'm builind an application which shows a map with the google api. Using the user input address, I query the API for directions to a destination. The API returns me a XML response which I parse to build my directions objects and show informations to the user.

Everything works but some of my xpath.evaluate() use do not work as I expect. For example this response :

Google Maps Response

When I use :

NodeList legList = (NodeList) xpath.evaluate("//route/leg",
                    response, XPathConstants.NODE);

Even //legshould do the job right?

When I do a legList.getLength(), it gives me 23 but there are only two leg in the response. Do you know why this strange behavior is happening? I read about XML Namespace but I still don't know what to do, should I specidfy a namespace even if the answer doesn't contain any, and if yes, why do I have to?

2
  • For the given response //leg and //route/leg are equivalent. They're not necessarily equivalent in all possible responses. Have you tried /route/leg? What are the nodes in legList? Commented Mar 13, 2012 at 13:52
  • 1
    On my JVM (Sun JDK1.6.0_14), requesting XPathConstants.NODE, returns type: com.sun.org.apache.xerces.internal.dom.DeferredElementImpl - which also implements the NodeList interface. So I believe it is reporting the length as the number of child nodes of the first <leg> element it found in the Xml. Commented Mar 13, 2012 at 14:43

3 Answers 3

1

You need to use

    NodeList legList = (NodeList) xpath.evaluate(expr,
            xml, XPathConstants.NODESET);
Sign up to request clarification or add additional context in comments.

Comments

1

If you want a NodeList UseXPathConstants.NODESET instead of XPathConstants.NODE (check here for the mappings: http://docs.oracle.com/javase/6/docs/api/javax/xml/xpath/XPathConstants.html#NODESET) like this:

NodeList legList = (NodeList) xpath.evaluate("//route/leg", response, XPathConstants.NODESET);

2 Comments

The think I don't understand is why the count gave me 23, the <leg> tag is a node right? I thought it would add every leg node it would find to the node list. But instead it looks like it added all of the children, am I right?
@David: See my comment above. Any element node from the Xml can present itself as a NodeList (which is an interface), because it can potentially have a list of child nodes. (Probably textNode type wouldn't implement NodeList, since it cannot have any children.)
0

try this code.

NodeList legList = (NodeList) xpath.evaluate("/route/leg",
                response, XPathConstants.NODESET);

NODESET is return the NodeList while XPathConstants.NODE is return single Object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.