如何通过NSXMLParser加载xml文件

Wal*_*est 0 nsxmlparser ios swift

我找到了NSXMLParser构造函数使用URL的示例,例如:

NSXMLParser(contentsOfURL: (NSURL(string:"http://images.apple.com/main/rss/hotnews/hotnews.rss")))!
Run Code Online (Sandbox Code Playgroud)

但是我找不到如何将它与项目中的xml文件一起使用.

Aar*_*den 7

为了获取路径到应用程序的包里面使用的资源NSBundlepathForResource:ofType:方法,如:

 var path = NSBundle.mainBundle().pathForResource("MyFile", ofType: "xml")
Run Code Online (Sandbox Code Playgroud)

您可以从路径创建文件URL并将其传递给NSXMLParser.

    var parser: NSXMLParser?
    let path = NSBundle.mainBundle().pathForResource("MyFile", ofType: "xml")
    if path != nil {
        parser = NSXMLParser(contentsOfURL: NSURL(fileURLWithPath: path!))
    } else {
        NSLog("Failed to find MyFile.xml")
    }

    if parser != nil {
        // Do stuff with the parser here.
    }
Run Code Online (Sandbox Code Playgroud)