无法使用Swift中的SWXMLHash返回值解析XML

时间:2015-10-10 13:56:05

标签: xml swift swift2 swxmlhash

当我尝试显示" 50%"时,它取自

  

预测>区域>预测期>文字> probability_of_precipitation

它提出了" nil"在故事板上的标签上。

我有这个XML片段,位于公共ftp地址(如下面的代码所示)

<forecast>
        <area aac="VIC_FA001" description="Victoria" type="region"/>
        <area aac="VIC_PW001" description="Mallee" type="public-district" parent-aac="VIC_FA001"/>
        <area aac="VIC_PT043" description="Mildura" type="location" parent-aac="VIC_PW001">
            <forecast-period index="0" start-time-local="12pm" end-time-local="12:30pm" start-time-utc="1:00pm" end-time-utc="1:30pm">
                <element type="forecast_icon_code">16</element>
                <text type="precis">Shower or two. Possible storm.</text>
                <text type="probability_of_precipitation">50%</text>
            </forecast-period>
        </area>
</forecast>

这是我的代码:

let urlStringMax = "ftp://ftp2.bom.gov.au/anon/gen/fwo/IDV10753.xml"

    if let urlMax = NSURL(string: urlStringMax)
    {
        if let data = try? NSData(contentsOfURL: urlMax, options: [])
        {
            let xml = SWXMLHash.parse(data)

            let precipForecast = xml["forecast"]["area"][2]["forecast-period"][0]["text"][type="probability_of_precipitation"].element?.text

            maxTemp.text = "\(precipForecast)"
        }
    }

1 个答案:

答案 0 :(得分:1)

第五件事:您忘记在查询开头包含["product"]

然后您使用正确语法的最后一次订阅[type="probability_of_precipitation"]

这是获得价值的两种不同方式。

1-按索引:

let precipForecast = xml["product"]["forecast"]["area"][2]["forecast-period"][0]["text"][1].element?.text

2-属性,.withAttr。在您的情况下,对于&#34;键入&#34;:

do {
    let precipForecast = try xml["product"]["forecast"]["area"][2]["forecast-period"][0]["text"].withAttr("type", "probability_of_precipitation").element?.text
} catch {
    print(error)
}

或者如果你想要一个可选的:

let precipForecast = try? xml["product"]["forecast"]["area"][2]["forecast-period"][0]["text"].withAttr("type", "probability_of_precipitation").element?.text