如何创建一个API方法来读取iPhone中的XML数据?
我正在创建一个基于 XML 的应用程序,其中我必须从 XML 获取数据并在 iPhone 上显示。我有一个正在获取数据的网址。但我不知道如何创建用于 XML 解析的 API 方法。
如何创建一个API方法来确定url返回的数据是XML格式还是JSON格式?
I am creating an XML based application in which I have to fetch data from XML and show on iPhone. I have a url through which the data is being fetched. But I don't know how to create the API method for XML parsing.
How can I create an API method for determining the data returned by the url is in XML format or in JSON format?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
请参阅 Apple 的 XMLPerformance 项目以获取示例代码。
Look at Apple's XMLPerformance project for sample code.
您必须使用 NSXMLParser
You have to use the NSXMLParser
您不需要创建自定义 API。查看 NSXMLParser 和 libxml2。这方面并不差,你只需要学会使用它即可。一旦你看到代码,它应该从
You don't need to create a custom API. Check out NSXMLParser, and libxml2. Is not bad at this you just have to learn to use it. Once you see the code it should make since
有一个关于如何使用 NSXML 解析器的很好的教程
您基本上会对 didStart 和 didEndelements 感兴趣。当文档解析结束时,会调用不同的方法。
There is a nice tutorial on how you can use the NSXML parser here.
You have to implement the parser delegate and get the parsed values from those delegate methods.
You would be basically interested in didStart and didEndelements. A different method is called when the document parsing is over.
这是我在项目中使用的 xml 解析器代码,它应该允许您解析大多数 XML 文件:
-
-
-
按以下方式使用(此示例用于分析 rss feed:
如果您想了解更多方法,请检查 XMLNode.h需要更复杂的分析
Here is the xml parser code I'm using in my projects, it should allow you to parse most XML files :
-
-
-
use this as following (this sample is to analyze a rss feed :
Check XMLNode.h for more methods if you need a more complex analysis
听起来您的问题不是如何解析 XML,而是如何从 Web 下载 XML 文档到 NSData 对象等。
您可以使用开源的
ASIHTTPRequest
框架快速下载您的XML数据。查看有关设置异步请求的操作文档 。假设 URL 正确并且请求成功,XML 数据将存储在请求的
responseData
属性中。然后,您可以使用各种方法来解析此属性中的 XML 数据。我推荐
libxml2
,因为它是最快的。但此时您可以使用任何您想要的解析器引擎和方法。It sounds like your question is not how to parse XML, but how to download an XML document from the web into an
NSData
object, or the like.You can use the open source
ASIHTTPRequest
framework to quickly download your XML data. Take a look at the how-to document on setting up an asynchronous request.Assuming the URL is correct and the request is successful, the XML data will be stored in the request's
responseData
property.You can then use various methods for parsing the XML data in this property. I recommend
libxml2
, as it is the fastest. But you could use whatever parser engine and method you want, at this point.