【问题标题】:How to load xml file through NSXMLParser如何通过 NSXMLParser 加载 xml 文件
【发布时间】:2015-08-09 00:51:32
【问题描述】:

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

NSXMLParser(contentsOfURL: (NSURL(string:"http://images.apple.com/main/rss/hotnews/hotnews.rss")))!

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

【问题讨论】:

    标签: ios swift nsxmlparser


    【解决方案1】:

    要获取应用程序包中资源的路径,请使用NSBundlepathForResource:ofType: 方法,例如:

     var path = NSBundle.mainBundle().pathForResource("MyFile", ofType: "xml")
    

    您可以从路径创建文件 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.
        }
    

    【讨论】:

      【解决方案2】:

      已接受答案的 Swift 4 版本

      var parser : XMLParser?
          if let path = Bundle.main.path(forResource: "File", ofType: "xml") {
              parser = XMLParser(contentsOf: URL(fileURLWithPath: path))
      
              if parser?.parse() ?? false {
      
              }else {
                  print("Unable to parse")
              }
      
          }else {
              print("File read error")
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-18
        相关资源
        最近更新 更多