To parse an XML document we begin by creating a class or struct that conforms to the NSXMLParaseDelegate
protocol. In our example, we will name the class MyXMLParser
. Our MyXMLParser
class definition will look like this:
class MyXMLParser: NSObject, NSXMLParserDelegate { }
Within the MyXMLParser
class, we will add three properties that will be used by the parser while it is parsing the document. These three properties are:
books
: This property will be an optional array that will contain the list of books defined in the XML documentbook
: This will be an optional instance of theBook
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
These properties will be defined like this:
var books: [Book]? var book: Book? var elementData = ""
Now we need to add the NSXMLParserDelegate
methods. The first one we add will be the parseXmlString...