gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:57:25 25 4
gpt4 key购买 nike

当我尝试显示取自

的“50%”时

forecast > area > forecast-period > text > probability_of_precipitation

它在我的 Storyboard标签上出现了“nil”。

我有这个 XML 片段,它位于一个公共(public) 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"] 下标时没有使用正确的语法。

这是获取值(value)的两种不同方式。

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

关于xml - 无法在 Swift 中使用 SWXMLHash 返回解析 XML 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33054744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com