iPhone访问本地XML文件

Ter*_*ary 2 xml iphone nsurlconnection nsxmlparser

我有一个iPhone应用程序,可以从URL进行XML解析.我在我的资源目录(在XCode中)有一个sample.xml文件,我想使用它.

如何在代码中引用此文件?我已经尝试了@"sample.xml"作为URL,它似乎无法找到它.

Tim*_*Tim 5

首先,小心地将URL作为路径传递,反之亦然 - 您可能无法轻易地将两者交换.如果必须,请尝试使用前缀文件的路径file://.

至于查找路径,可以使用NSBundle方法pathForResource:ofType::

NSString *xmlFilePath = [[NSBundle mainBundle] pathForResource:@"sample"
                                                        ofType:@"xml"];
NSString *xmlFileContents = [NSString stringWithContentsOfFile:xmlFilePath];
Run Code Online (Sandbox Code Playgroud)