2015-11-19 161 views
0

我想找到一种方法在Swift中从Web数据中提取多个项目。我期待调用的URL后迅速提取从以下XML数据驱动器的ID:关于从Web数据中提取信息的建议(Swift)

查看源代码: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." 

    } 

} 

回答

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.") 
} 
+0

这工作完美,谢谢花时间写一个解决方案,我现在应该能够使用收集的驱动程序数据 – qwerty567111