Taichi Kato
Taichi Kato

Reputation: 602

How can I get a specific attribute from a XML in SWIFT with NSXMLParser

I need to retrieve a specific attribute from an XML File specifically <reading type="NPSI_PM25_3HR" value="xx"/> under <id>NRS</id> then parse it as a variable which later I would like to print, but I can not find any way to do this in Swift. Is there any way that I can do this? Thanks!

Upvotes: 2

Views: 1519

Answers (1)

Taichi Kato
Taichi Kato

Reputation: 602

I figured it out by myself. Here is what I did in order to retrieve the value in case there's someone who encounter the same problem as me.

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)
        }

    }
}

Upvotes: 5

Related Questions