从Web数据中提取信息的建议(Swift)

时间:2015-11-19 19:57:30

标签: ios xml swift

我想找到一种从Swift中的Web数据中提取多个项目的方法。我想在swift中调用URL后从以下XML数据中提取驱动程序ID:

view-source:http://ergast.com/api/f1/current/last/results(在Chrome中查看来源)

目前我有一个只挑出第一个值的解决方案。理想情况下,我想选择所有值并将它们排列在一个数组中供以后使用。

    var wasSuccessful = false

    let attemptedUrl = NSURL(string: "http://ergast.com/api/f1/current/last/results")

    if let url = attemptedUrl {

        let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in

            if let urlContent = data {

                let webContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding)

                let websiteArray = webContent?.componentsSeparatedByString("<Driver driverId=\"")

                if websiteArray!.count > 1 {

                    let driverArray = websiteArray![1].componentsSeparatedByString("\" code=")

                    if driverArray.count > 1 {

                        wasSuccessful = true

                        let driverSummary = driverArray[0]

                        dispatch_async(dispatch_get_main_queue(), { () -> Void in

                            self.lblDrivers.text = driverSummary // just to confirm drivers are showing up

                        })

                    }

                }

            }

            if wasSuccessful == false {

                self.lblDrivers.text = "Sorry, we could not find the results."

            }

        }

        task.resume()

    } else { //if url couldnt be created

        self.lblDrivers.text = "Sorry, we could not find the results."

    }

}

2 个答案:

答案 0 :(得分:0)

您可以使用NSXMLParser。这是关于如何使用该类来解析XML文件的tutorial

然而,如果您从未使用过NSXMLParser,那么有许多库可以使XML解析更容易。

以下是您可以尝试的一小部分XMLParser库:

答案 1 :(得分:0)

此库可以很好地解决您的问题:Fuzi

它支持XPath和CSS查询。在您的情况下,定义带有前缀“ns”的XML名称空间“http://ergast.com/mrd/1.4”,然后使用XPath查询“// ns:Driver”将所有名为Driver的元素作为序列返回。

我们需要定义名称空间的原因是您提供的XML在名称空间“http://ergast.com/mrd/1.4”中具有其根元素

如果您不熟悉XPath,请参阅:https://en.wikipedia.org/wiki/XPath

import Fuzi

let attemptedUrl = NSURL(string: "http://ergast.com/api/f1/current/last/results")

if let url = attemptedUrl {
  let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
    do {
      guard let data = data else {
        print("failed to get data")
        return
      }
      let doc = try XMLDocument(data: data)
      doc.definePrefix("ns", defaultNamespace: "http://ergast.com/mrd/1.4")

      let drivers = doc.xpath("//ns:Driver")
      for driver in drivers {
        print(driver["driverId"])
        print(driver["code"])
        print(driver["url"])
      }

      if drivers.isEmpty {
        print("No drivers found")
      }
    } catch let error {
      print(error)
    }
  }
  task.resume()
} else { //if url couldnt be created
  print("Sorry, we could not find the results.")
}