2015-11-19 155 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