Learn How To Do XML Parsing in Swift

In this tutorial, learn how to do XML Parsing in Swift first  we will create simple application called XMLParsingDemo, which describes how to parse XML data.

Following are the steps, which explains how to fetch and read XML data and display it in tableview.

Step 1: Create Single View Application Open Xcode 6 and create one new project with single view application template.

Screen Shot 2015-04-20 at 1.35.53 PM

In the next step enter XMLParsingDemo as a product name and also select swift as a language as shown in below figure.

Screen Shot 2015-04-20 at 1.36.35 PM

Step 2: Design User Interface

To design user interface open Main.storyboard file and in that one ViewController. In that ViewController add one
tableview to display data.

Screen Shot 2015-04-20 at 1.38.27 PM

Step 3: Implementation of XML Parsing To parse XML Data declare following variable in your class.

var parser = NSXMLParser()
var posts = NSMutableArray()
var elements = NSMutableDictionary()
var element = NSString()
var title1 = NSMutableString()
var date = NSMutableString()

Now from viewDidLoad method calling beginParsing method in that doing initialization of parser object, set
NSXMLParserDelegate and then start XML parsing.

func beginParsing()
{
posts = [] parser = NSXMLParser(contentsOfURL: (NSURL.(String:”http://images.apple.com/main/rss/hotnews/hotnews.rss”)))!
parser.delegate = self
parser.parse()
tbData!.reloadData()
}

Step 4: Implementation of Parser Delegate

class ViewController: UIViewController, NSXMLParserDelegate

During parsing, when parser finds any new element it calls the below delegate method. In this method allocate variable
when parser find the item element.
func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName:
String!, attributes attributeDict: [NSObject : AnyObject]!)
{
element = elementName
if (elementName as NSString).isEqualToString(“item”)
{
elements = NSMutableDictionary.alloc()
elements = [:] title1 = NSMutableString.alloc()
title1 = “”
date = NSMutableString.alloc()
date = “”
}
}

After that when it finds new character it calls the below delegate method. In this method append all character in mutable string for particular element.
func parser(parser: NSXMLParser!, foundCharacters string: String!)
{
if element.isEqualToString(“title”) {
title1.appendString(string)
} else if element.isEqualToString(“pubDate”) {
date.appendString(string)
}
}

When parser finds the end of element it calls the below delegate method. In that just store the feed data in dictionary and then add that dictionary in array.
func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!)
{
if (elementName as NSString).isEqualToString(“item”) {
if !title1.isEqual(nil) {
elements.setObject(title1, forKey: “title”)
}
if !date.isEqual(nil) {
elements.setObject(date, forKey: “date”)
}

posts.addObject(elements)
}
}

Step 5: Display XML data in tableview After xml parsing display data from array in tableview using below methods.

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return posts.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{

let identifier = “Cell”
var cell: TableViewCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as? TableViewCell
if cell == nil {
tableView.registerNib(UINib(nibName: “CustomCellOne”, bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? TableViewCell
}
cell.lblTitle?.text=posts.objectAtIndex(indexPath.row).valueForKey(“title”) as NSString
cell.lblDetail?.text=posts.objectAtIndex(indexPath.row).valueForKey(“date”) as NSString

return cell
}

 

OUTPUT ->

Screen Shot 2015-04-20 at 1.26.04 PM