David Seek David Seek - 2 years ago 213
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.

Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download