David Seek David Seek - 11 months ago 97
Swift Question

Swift / XMLParser / How to parse a specific element / CheatyXML

I want to parse and download the current EUR - USD exchange rate. I have descided to get the value from the European Central Bank Feed.

I'm using the CheatyXML XMLParser extension.

How can I get the USD value?

enter image description here

With the following code, I get the value: "European Central Bank". My String is an optional on porpuse. Because my app crashed like 1 trillion times during finding the correct code to get the currency rate...

let feedUrl = NSURL(string: "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml")
let parser: XMLParser! = XMLParser(contentsOfURL: feedUrl!)
let exchangeString: String? = parser["gesmes:Sender"]["gesmes:name"].string // Returns an optional String

How do I get the value of
<Cube currency="USD"

let blogName: String? = parser["Cube"]["Cube"].string // Returns an optional String

Is not working.
Help is very appreciated.


You need to go one level deeper (there's three "Cube" fields), then get the attributes and finally subscript with the right key, for example:

parser["Cube"]["Cube"]["Cube"].attributes["currency"] as? String  // "USD"

parser["Cube"]["Cube"]["Cube"].attributes["rate"] as? String // "1.1287"