如何在Swift ios中使用JSON输出解析XML?

时间:2016-03-10 03:14:05

标签: ios json xml swift nsxmlparser

我正在尝试解析soap api的输出。

'%TY-%Tm-%Td %TH:%TM:%TS %p\n'

我一直在手动解析它

<string xmlns="webservices.fmx.bz/">
{ "ui": [ { "t": "1234", "vid": "123", "cn": "Company Name" } ] }
</string>

任何人都知道我可以使用的更简单的解决方案或库吗?

2 个答案:

答案 0 :(得分:0)

想出怎么做...... 必须清理数据字符串然后转换回nsdata

 Alamofire.request(.POST, emconOWO, parameters: params) .responseString { response in
        print("Success: \(response.result.isSuccess)")
//            print(response.result.value)

        var responseString = response.result.value?.stringByReplacingOccurrencesOfString("\r\n", withString: "")
        responseString = responseString?.stringByReplacingOccurrencesOfString("<string xmlns=\"webservices.fmx.bz/\">", withString: "")
        responseString = responseString?.stringByReplacingOccurrencesOfString("<?xml version=\"1.0\" encoding=\"utf-8\"?>", withString: "")
        responseString = responseString?.stringByReplacingOccurrencesOfString("</string>", withString: "")
     responseString = responseString?.stringByReplacingOccurrencesOfString("\\", withString: "")

        print(responseString)

  let data = responseString!.dataUsingEncoding(NSUTF8StringEncoding)
        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print(jsonResult)
            }

答案 1 :(得分:0)

iOS提供了一个内置的JSON解析器,它完全解析JSON字符串并构建一个代表JSON结构的字典。

但是,iOS不提供类似的XML方法。 iOS提供的NSXMLParser使用&#34;事件驱动&#34;模型。即:解析器通知代表事件,我们的工作是根据元素构建结构。

JSON方法相对容易,因为我们可以简单地查询解析后的数据结构以获取所需的对象。

但是,我发现有一个库在Swift中对XML执行类似的活动。你可以找到它here

请检查它,您应该能够解析XML并使用它构建解析对象。