【问题标题】:Parsing XML on iOS在 iOS 上解析 XML
【发布时间】:2012-08-05 13:57:31
【问题描述】:

我正在使用我正在编写的 XML 应用程序的教程,但我不知道如何将 NSURL 更改为 XML 文件在 iPhone 上的位置。

//XMLAppDelegate.m 

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    NSURL *url = [[NSURL alloc] initWithString:@"sites.google.com/site/iphonesdktutorials/xml/...";
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
    //Initialize the delegate. 
    XMLParser *parser = [[XMLParser alloc] initXMLParser];
    //Set delegate [xmlParser setDelegate:parser]; 
    BOOL success = [xmlParser parse]; 
    if(success) 
        NSLog(@"No Errors"); 
    else 
        NSLog(@"Error Error Error!!!"); 
    [window addSubview:[navigationController view]]; 
    [window makeKeyAndVisible]; 
}

【问题讨论】:

  • 可能是NSURL *url = [[NSURL alloc] initWithString:@"http://sites.google.com/site/iphonesdktutorials/xml/Books.xml"];?
  • 请发布您用于加载数据文件的代码。
  • 我不希望它从 Web 服务中读取。我需要 iPhone 上的 XML 文件。该应用程序必须从那里读取它
  • //XMLAppDelegate.m - (void)applicationDidFinishLaunching:(UIApplication *)application { NSURL *url = [[NSURL alloc] initWithString:@"sites.google.com/site/iphonesdktutorials/xml/Books.xml"]; NSXMLParser *xmlParser = [[NSXMLParser alloc ] initWithContentsOfURL:url]; //初始化委托 XMLParser *parser = [[XMLParser alloc] initXMLParser]; //设置委托 [xmlParser setDelegate:parser]; BOOL success = [xmlParser parse]; if(success) NSLog(@ "No Errors"); else NSLog(@"Error Error Error!!!"); [window addSubview:[navigationController view]]; [window makeKeyAndVisible]; }
  • 抱歉,无法将上面的代码格式化为好看的。该代码可在上面的教程链接中找到

标签: ios objective-c xml xml-parsing


【解决方案1】:

NSURL 提供了轻松创建文件 URL 的方法,但如果文件是应用程序的资源之一,获取所需 URL 的最简单方法是使用 NSBundle:

NSURL *url = [[NSBundle mainBundle] URLForResource:@"MyDataFile" withExtension:@"xml"];

否则,您可能需要查看+[NSURL fileURLWithPath:]

【讨论】:

  • 好的,所以我将 Url 代码更改为下面的代码,但是它会崩溃 NSURL *url = [[NSBundle mainBundle] URLForResource:@"MyDataFile" withExtension:@"xml"];我需要显示它的文件位置吗?
  • 导致崩溃的原因是什么?另外,您的 XML 文件存储在哪里?它是在您的应用程序包中、在 Documents 文件夹中还是在其他地方?
  • 我相信是 NSURL 函数导致了崩溃。 xml 文件被放入资源文件夹。我不确定是否需要将其放入直接路径或将其放在其他地方。
【解决方案2】:

我相信是 NSURL 函数导致了崩溃。 xml 文件被放入资源文件夹。我不确定我是否需要将其放入直接路径或将其放在其他地方

【讨论】:

    猜你喜欢
    • 2012-11-04
    • 2014-05-13
    • 2012-08-11
    • 2014-05-22
    • 2010-11-04
    • 2014-04-17
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多