如何使用 iPhone 从 Google Directions API 解析距离数据?
我试图获取两个地方之间的距离(通过道路),并且我发现 http 请求将返回包含以下数据的 XML
http://code.google.com/apis/maps/documentation/directions/#XML
但我不知道如何使用 NSXMLParser得到总距离。我假设使用该
parser:didStartElement:namespaceURI:qualifiedName:attributes
方法,但不确定它是如何工作的。我想我想要的元素是“方向”,但有几个类似的元素。我如何指定我想要哪一个?它与“attributes”参数有关吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSXMLParser
是一个 SAX 解析器,这意味着您必须在处理文档时为各种解析事件提供回调方法。您链接到的 Google 文档让我认为这些文档并不是很大,因此我个人不会使用 SAX 解析器。DOM 解析器(例如
NSXMLDocument
)更容易使用,但不幸的是 Apple 并未在 iOS SDK 中包含NSXMLDocument
。有多种替代方案,包括 TouchXML。如果您只关心总距离,而不关心每条腿或每一步的距离,那么简单的 XPath 查询将为您获取所有距离:
//leg/step/distance/value
。循环遍历它们并总结它们。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 includeNSXMLDocument
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.您使用 didStartElement 来查找所需的元素,而不是使用foundCharacters 方法来收集标签的内容(可以调用多个标签),因此只有当调用 didEndElement 方法时,您才能将标签的内容用于您想要的任何内容。
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.