Parsing XML documents
For parsing XML documents, perform the following steps:
Create a class that will conform to the
NSXMLParaseDelegate
protocol. Let's name the classMyXMLParser
. TheMyXMLParser
class definition will look like this:class MyXMLParser: NSObject, NSXMLParserDelegate { }
Next, we will need to add three properties that will be used by the parser while it is parsing the document. These three properties are as follows:
books: This property will be an optional array that will contains the list of books defined in the XML document
book: This will be an optional instance of the
Book
class that represents the current book being parsed within the XML documentelementData: This will be an instance of the string class that contains the value of the current element that is being parsed
Add the properties to the
MyXMLParaser
class with the following code:var books: [Book]? var book: Book? var elementData = ""
Let's add the
parseXmlString
method that will be used to start theNSXMLParser
:func...