从应用程序包中解析 XML,而不是 URL

发布于 2025-01-07 06:39:26 字数 183 浏览 3 评论 0原文

我正在构建一个从在线服务器解析 XML 的应用程序。我想在本地缓存 XML 文件 24 小时。如何更改以下代码以从资源目录中的文件中读取?

parser = [[NSXMLParser alloc] initWithContentsOfURL: [NSURL URLWithString:url]];

I'm building an application that parses XML from an online server. I want to cache the XML file locally for 24 hours. How can I change the following code to read from a file in my resource directory?

parser = [[NSXMLParser alloc] initWithContentsOfURL: [NSURL URLWithString:url]];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故事灯 2025-01-14 06:39:26

您可以像下面这样获取 xml 文件的路径:

NSString* path = [[NSBundle mainBundle] pathForResource:@"yourxml" ofType:@"xml"];

然后像下面这样获取 NSData 实例:

NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:path];

最后调用

NSXMLParserinitWithData 方法。

但是您无法修改应用程序包的内容。捆绑包中的文件(您请求的资源目录)无法修改。

有不同的方法可以做到这一点:

  • 从网络上抓取文件并将其保存在属性列表文件中
  • 使用NSFileManager类来保存和读取您的xml文件

NSFileManager的示例>:

NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectoryPath = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"yourxml.xml"];

该代码片段获取文档目录中包含的 xml 文件路径。这意味着那里已经有一个文件了。有关详细信息,请参阅 NSFileManager 类如何保存您的应用程序-data-with-nscoding-and-nsfilemanager

希望有帮助。

You can obtain the path for your xml file like the following:

NSString* path = [[NSBundle mainBundle] pathForResource:@"yourxml" ofType:@"xml"];

and then obtain a NSData instance like the following:

NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:path];

and finally call

initWithData method of NSXMLParser.

But you cannot modify the content of your application bundle. Files in the bundle (the resources directory you asked for) cannot be modified.

There are different way to do it:

  • grab the file from the web and save it in a property-list file
  • use NSFileManager class to save and read your xml file

An example with NSFileManager:

NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectoryPath = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"yourxml.xml"];

The snippet grab the xml file path contained in your Documents directory. It means that there is already a file there. For further info see NSFileManager class and how-to-save-your-app-data-with-nscoding-and-nsfilemanager

Hope it helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文