简体   繁体   English

无法使用SWXMLHash从Web服务解析XML

[英]Unable to parse XML from Webservice using SWXMLHash

I have the following code using SWXMLHash - the XML parser however does not appear to be able to process it. 我有以下使用SWXMLHash的代码-但是XML解析器似乎无法处理它。 I have checked the URL to make sure it returns data: 我检查了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

The XML I get from the url is like this (tags are closed off - I just haven't included them): 我从url获得的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"/>

应用运行时的局部变量视图

There are multiple Sensor elements but only one Sensors element. 有多个Sensor元素,但只有一个Sensors元素。

So, instead of: 因此,代替:

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

You should have something like: 您应该具有以下内容:

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

That would grab the first sensor out of the group that is returned. 这将使第一个传感器脱离返回的组。

To loop over the sensors, you'll have something like: 要遍历传感器,您将获得以下内容:

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

Hope this helps! 希望这可以帮助!

OK. 好。 I have solved the problem. 我已经解决了问题。 The issue was with the XML file i receive from the server. 问题出在我从服务器收到的XML文件中。 It looks like it is UTF-8 format, but the document says it is UTF-16. 看起来它是UTF-8格式,但是文档说它是UTF-16。 So, I now convert the data object received into a UTF-8 NSString, and then cast that into a String! 因此,我现在将接收到的数据对象转换为UTF-8 NSString,然后将其转换为String! Please see the code below: 请参见下面的代码:

    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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM