繁体   English   中英

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

[英]Can't return value parsing XML using SWXMLHash in Swift

当我尝试显示“ 50%”时,该值取自

预报>区域>预报期>文本>降水概率

它在情节提要中的标签上标有“ 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)"
        }
    }

首先,您忘了在查询开始时包含["product"]

那么您最后一次使用[type="probability_of_precipitation"]下标就没有使用正确的语法。

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

1-按索引:

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

2-按属性,带有.withAttr 对于您的情况,对于“类型”:

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

暂无
暂无

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

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