Parsing XML Tutorial

In this tutorial an xml file will be parsed using a NSXMLParser object. The results of the parsing will be displayed in  a Table View. This tutorial is made with Xcode 7.3.1 and built for iOS 9.3

Open Xcode and create a new Single View Application. For product name, use IOS9XMLParserTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.


Remove the View Controller from the Storyboard and drag a Navigation Controller to the empty canvas. The Navigation Controller will automatically put a Table View Controller onto the storyboard. When the initial View Controller is deleted there isn't a starting point defined. Select the Navigation Controller and go to the Attribute Inspector. In the View Controller Section select the "Is Initial View Controller" checkbox.

Double-click the Title Bar of the Table View Controller and set the title to "Books". Select the Table View Cell and go to the Attributes Inspector. In the Table View Cell section set the Style Attribute to Subtitle.

The Storyboard should look like this

Since we have deleted the View Controller from the Storyboard we can also delete the ViewController.swift file. Add a new file to the project, select iOS->Source->Cocoa Touch Class. Name it TableViewController and make it a subclass of UITableViewController.

Go to the Storyboard and select the Table View Controller. go to the Identity inspector and in the Custom Class section change the class to TableViewController. 

Add a new file to the project, select iOS->Source->Swift File. Name it books.xml

Open the Books.xml file and change it with the following contents.

<?xml version="1.0"?>
    <book id="1">
        <title>To Kill a Mockingbird</title>
        <author>Harper Lee</author>
    <book id="2">
        <author>George Orwell</author>
    <book id="3">
        <title>The Lord of the Rings</title>
        <author>J.R.R Tolkien</author>
    <book id="4">
        <title>The Catcher in the Rye</title>
        <author>J.D. Salinger</author>
    <book id="5">
        <title>The Great Gatsby</title>
        <author>F. Scott Fitzgerald</author>

Add a new File to the Project, which will be used as datamodel for the different items of the xml file. select iOS->Source->Swift File. Name it Book.swift. Change the Book.swift file to

import Foundation

class Book {
    var bookTitle: String = String()
    var bookAuthor: String = String()

Go to the tableViewController.swift file and add the following properties.

var books: [Book] = []
var eName: String = String()
var bookTitle = String()
var bookAuthor = String()

Change the viewDidLoad method to

override func viewDidLoad() {
    if let path = NSBundle.mainBundle().URLForResource("books", withExtension: "xml") {
        if let parser = NSXMLParser(contentsOfURL: path) {
            parser.delegate = self

The NSXMLParser object parses the books.xml file inside the bundle. Add the following table View data source delegate methods

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return books.count
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
    let book = books[indexPath.row]
    cell.textLabel?.text = book.bookTitle
    cell.detailTextLabel?.text = book.bookAuthor

    return cell

The title and author of the books will be displayed into the Table View with the contents of the books array. Next, implement the NSXMLParser delegate methods.

// 1
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
    eName = elementName
    if elementName == "book" {
        bookTitle = String()
        bookAuthor = String()
// 2  
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
    if elementName == "book" {
    let book = Book()
    book.bookTitle = bookTitle
    book.bookAuthor = bookAuthor
// 3
func parser(parser: NSXMLParser, foundCharacters string: String) {
    let data = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    if (!data.isEmpty) {
        if eName == "title" {
            bookTitle += data
        } else if eName == "author" {
            bookAuthor += data
  1. This method is sent by the parser object when the start tag of "<book>" is encountered.
  2. This method is sent by the parser object when the end tag of  "</book>" is encountered.
  3. Here the actual parsing is executed. The title and author tags will be parsed and the corresponding properties will be initialized.

Build and Run the project. Inside the TableViewController the book tiles and authors will be displayed.

You can download the source code of the IOS9XMLParserTutorial at the ioscreator repository on Github.