无法使用SWXMLHash从Webservice解析XML

时间:2017-01-09 14:39:29

标签: swift swxmlhash

我使用SWXMLHash有以下代码 - 但XML解析器似乎无法处理它。我检查了URL以确保它返回数据:

let baseUrl = "http://apps.hha.co.uk/mis/Api/getlivesensors.aspx?key=6fb21537-fb4e-4fe4-b07a-d8d68567c9d1"
        var request = URLRequest(url: NSURL(string: baseUrl)! as URL)
        let session = URLSession.shared
        request.httpMethod = "GET"

        //var err: NSError?

        let task = session.dataTask(with: request as URLRequest) {
            (data, response, error) in

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

            let xml = SWXMLHash.parse(data!)

            if (xml["Sensors"]["Sensor"]["Name"].element?.text) != nil
            //if (xml["Sensors"]["Sensor"]["Name"].element?.text) != nil 
            {
                self.sensors.add(xml["Sensors"]["Sensor"]["Name"].element?.text as Any)
            }

            DispatchQueue.main.async(execute : {
                print(self.sensors)
            })

        }
        task.resume()
        // but obviously don't try to use it here here

我从网址获取的XML是这样的(标签已关闭 - 我只是没有包含它们):

<Sensors>
<Sensor>
<ID>12</ID>
<Name>EFM W.level</Name>
<Series>Level</Series>
<Unit>m</Unit>
<Values>
<Value CreatedOn="2017-01-08T13:50:00" Value="0.69"/>
<Value CreatedOn="2017-01-08T14:00:00" Value="0.72"/>
<Value CreatedOn="2017-01-08T14:10:00" Value="0.77"/>
<Value CreatedOn="2017-01-08T14:20:00" Value="0.82"/>
<Value CreatedOn="2017-01-08T14:30:00" Value="0.87"/>

A view of the local variables as the app runs

2 个答案:

答案 0 :(得分:1)

有多个Sensor元素,但只有一个Sensors元素。

所以,而不是:

xml["Sensors"]["Sensor"]["Name"].element?.text

你应该有类似的东西:

xml["Sensors"]["Sensor"][0]["Name"].element?.text

这会抓住返回的组中的第一个传感器。

要遍历传感器,您将拥有以下内容:

for sensor in xml["Sensors"]["Sensor"].all {
    sessors.add(sensor["Name"].element?.text)
}

希望这有帮助!

答案 1 :(得分:0)

行。我已经解决了这个问题。问题在于我从服务器收到的XML文件。看起来它是UTF-8格式,但文件说它是UTF-16。所以,我现在将收到的数据对象转换为UTF-8 NSString,然后将其转换为String!请参阅以下代码:

    let baseUrl = "http://apps.hha.co.uk/mis/Api/getlivesensors.aspx?key=6fb21537-fb4e-4fe4-b07a-d8d68567c9d1"
    var request = URLRequest(url: NSURL(string: baseUrl)! as URL)
    let session = URLSession.shared
    request.httpMethod = "GET"

    let task = session.dataTask(with: request as URLRequest) {
        (data, response, error) in

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

        let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)?.replacingOccurrences(of: "utf-16", with: "utf-8")

        let xml = SWXMLHash.parse(dataString! as String)
        //let xml = SWXMLHash.parse(dataString!)

        if (xml["Sensors"]["Sensor"][0]["Name"].element?.text) != nil
        {
            self.sensors.add(xml["Sensors"]["Sensor"][0]["Name"].element?.text as Any)
        }

        DispatchQueue.main.async(execute : {
            print(self.sensors)
        })

    }
    task.resume()
    // but obviously don't try to use it here here