如何使用 NSXMLParser 从 SWIFT 中的 XML 获取特定属性

Tai*_*ato 2 xml parsing nsxmlparser ios swift

我需要从XML 文件<reading type="NPSI_PM25_3HR" value="xx"/>中检索特定 属性<id>NRS</id>,然后将其解析为变量,稍后我想打印该变量,但我找不到任何方法在 Swift 中执行此操作。有什么办法可以做到这一点吗?谢谢!

Tai*_*ato 5

我自己想出来了。这是我所做的,以便在有人遇到与我相同的问题时检索该值。

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
    if elementName == "reading"{
        if attributeDict["type"] == "NPSI_PM25_3HR"{
            let PSIValue = attributeDict["value"]! as String
            print(i)
            switch i {
                case 0:
                    area = "NRS"
                    nationalPSI = PSIValue
                case 1:
                    area = "North"
                case 2:
                    area = "South"
                case 3:
                    area = "Central"
                case 4:
                    area = "West"
                case 5:
                    area = "East"
                default:
                    area = ""
            }
            i += 1
            print(area, ":", PSIValue)
        }

    }
}
Run Code Online (Sandbox Code Playgroud)