Last active
November 8, 2021 16:26
-
-
Save dimkagithub/8b2341787503955670d0bce5898133bc to your computer and use it in GitHub Desktop.
XML Parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
struct Currency { | |
var date: Date? | |
var numCode: String? | |
var charCode: String? | |
var nominal: String? | |
var nominalDouble: Double? | |
var name: String? | |
var value: String? | |
var valueDouble: Double? | |
} | |
class XMLParcer: NSObject, XMLParserDelegate { | |
var currencies = [Currency]() | |
var currentCurrency: Currency? | |
var currentDate: Date = Date() | |
var currentCharacters: String = "" | |
func parseXML() { | |
let url = URL(string: "https://www.cbr.ru/scripts/XML_daily.asp?date_req=") | |
let parser = XMLParser(contentsOf: url!) | |
parser?.delegate = self | |
parser?.parse() | |
for index in 0..<currencies.count { | |
currencies[index].date = currentDate | |
} | |
} | |
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String] = [:] ) { | |
if elementName == "ValCurs" { | |
if let currentDateString = attributeDict["Date"] { | |
let formatter = DateFormatter() | |
formatter.dateFormat = "dd.MM.yyyy" | |
currentDate = formatter.date(from: currentDateString)! | |
} | |
} | |
if elementName == "Valute" { | |
currentCurrency = Currency() | |
} | |
} | |
func parser(_ parser: XMLParser, foundCharacters string: String) { | |
currentCharacters = string | |
} | |
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { | |
if elementName == "NumCode"{ | |
currentCurrency?.numCode = currentCharacters | |
} | |
if elementName == "CharCode"{ | |
currentCurrency?.charCode = currentCharacters | |
} | |
if elementName == "Nominal"{ | |
currentCurrency?.nominal = currentCharacters | |
currentCurrency?.nominalDouble = Double(currentCharacters.replacingOccurrences(of: ",", with: ".")) | |
} | |
if elementName == "Name" { | |
currentCurrency?.name = currentCharacters | |
} | |
if elementName == "Value"{ | |
currentCurrency?.value = currentCharacters | |
currentCurrency?.valueDouble = Double(currentCharacters.replacingOccurrences(of: ",", with: ".")) | |
} | |
if elementName == "Valute" { | |
currencies.append(currentCurrency!) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment