如何在Swift中解析XML Web服务?

时间:2014-11-23 08:26:03

标签: xml swift nsxmlparser

我不知道如何解析我的下面的代码.. 有人可以

func callService(usr: String, pwdCode: String) {

    let url = NSURL(string: "http://inspect.dev.cbre.eu/SyncServices/api/jobmanagement/PlusContactAuthenticationPost")
    var xmlParse:NSString  = ""
    var data : NSData!
    let request = NSMutableURLRequest(URL: url!)
    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
     request.HTTPMethod = "POST"
    let dictionary = ["email": usr, "userPwd": pwdCode]
    var error: NSError?
    if let body = NSJSONSerialization.dataWithJSONObject(dictionary, options: nil, error: &error) {
        request.HTTPBody = body
    } else {
        println("JSON error: \(error)")
    }

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        (data, response, error) in
        println(NSString(data: data, encoding: NSUTF8StringEncoding))

        // xmlParse=NSString(data: data, encoding: NSUTF8StringEncoding)!
        // let data = (xmlParse as NSString).dataUsingEncoding(NSUTF8StringEncoding)
        // NSXMLParser(data : NSData)

        // xmlParse=NSString(data: data, encoding: NSUTF8StringEncoding)!
        // xmlParse=response
        // println(xmlParse)
    }
    task.resume()

}

3 个答案:

答案 0 :(得分:9)

对于任何仍在寻找的人,这里是我使用的代码,它可以很好地将xml响应转换为Dictionaries / Arrays,这要归功于SWXMLHash类......

UPDATED SWIFT 2.0

    let baseUrl = "http://www.example.com/file.xml"
    let request = NSMutableURLRequest(URL: NSURL(string: baseUrl)!)
    let session = NSURLSession.sharedSession()
    request.HTTPMethod = "GET"

    var err: NSError?

    let task = session.dataTaskWithRequest(request) {
        (data, response, error) in

        if data == nil {
            print("dataTaskWithRequest error: \(error)")
            return
        }

        let xml = SWXMLHash.parse(data)

        if let definition = xml["entry_list"]["entry"][0]["def"].element?.text {
            // ...
        }

        dispatch_async(dispatch_get_main_queue(),{
            // use main thread for UI updates
        })

    }
    task.resume()

答案 1 :(得分:7)

您应该在完成处理程序中使用NSXMLParser来获取请求:

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    (data, response, error) in

    if data == nil {
        println("dataTaskWithRequest error: \(error)")
        return
    }

    let parser = NSXMLParser(data: data)
    parser.delegate = self
    parser.parse()

    // you can now check the value of the `success` variable here
}
task.resume()

// but obviously don't try to use it here here

显然,上述假设您已(a)将视图控制器定义为符合NSXMLParserDelegate并且(b)已实施NSXMLParserDelegate方法,例如类似的东西:

var elementValue: String?
var success = false

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) {
    if elementName == "success" {
        elementValue = String()
    }
}

func parser(parser: NSXMLParser, foundCharacters string: String?) {
    if elementValue != nil {
        elementValue! += string
    }
}

func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
    if elementName == "success" {
        if elementValue == "true" {
            success = true
        }
        elementValue = nil
    }
}

func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
    println("parseErrorOccurred: \(parseError)")
}

答案 2 :(得分:0)

我使用了下面的Class Created从XML数据中获取Dictionary。

https://github.com/Bhaavik/BDXmlParser

您需要添加该课程 并只需调用下面的函数进行字典响应

  let objXmlParser = BbXmlParser()
  let  dictResponse  =  objXmlParser.getdictionaryFromXmlData(data!)
                        print(dictResponse)

在这里你去了字典。 :)