How to parse distance data with iphone from google directions api?
I'm trying to get the distance between two places (by way of roads), and I get that an http request will return a XML with the following data
http://code.google.com/apis/maps/documentation/directions/#XML
but I don't get how to use NSXMLParser to get the total distance. I would assume to use the
parser:didStartElement:namespaceURI:qualifiedName:attributes
method but not sure how this works. The element I would want I guess is "directions" but there's a couple elements like that. How do I specify which one I want? Does it have to do with 开发者_开发技巧the "attributes" parameter?
NSXMLParser
is a SAX parser, and that means you must provide callback methods for various parse events while the document is processed. The Google documentation you link to makes me think these documents are not terribly large, and so I would personally not use a SAX parser.
A DOM parser, such as NSXMLDocument
is much easier to use, but unfortunately Apple did not include NSXMLDocument
in the iOS SDK. There are several alternatives, including TouchXML.
If you only care about the total distance, and not the distance of each leg or step, then a simple XPath query will get all of the distances for you: //leg/step/distance/value
. Loop through them and sum them up.
You use didStartElement to find element you need, than you should use foundCharacters method to gather content of tag (it can be called more than ones), so only when didEndElement method is called you can use content of tag for whatever you want.
精彩评论