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?

Community
  • 1
  • 1
David
  • 1,101
  • 5
  • 19
  • 38
  • 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`? – beerbajay Mar 13 '12 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 element it found in the Xml. – Sam Goldberg Mar 13 '12 at 14:43

3 Answers3

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);
Francisco Paulo
  • 6,284
  • 26
  • 25
  • The think I don't understand is why the count gave me 23, the `` 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 Mar 13 '12 at 14:17
  • 1
    @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.) – Sam Goldberg Mar 13 '12 at 14:58
1

You need to use

    NodeList legList = (NodeList) xpath.evaluate(expr,
            xml, XPathConstants.NODESET);
Sam Goldberg
  • 6,711
  • 8
  • 52
  • 85
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.

Muhammad Saifuddin
  • 1,284
  • 11
  • 29