Thursday, February 14, 2013

xml parsing in iphone


Hello friends !! Here is my next post in the 'iPhone Tutorials ' Series .

It may occured to you guys , that you are downloading some content from internet and content is in the XML format . XML content is quite not a readable for customers / client , so we need to provide them the required content in a sorted way by parsing out elements from  the XML file 

Same is the we are going to do in this tutorial !

Steps for parsing XML format file
 
1)  get the xml file and put it in the resource folder of project
2) make an object of NSXmlParser and then use it for parsing the xml file
3) override the delegate functions for NSXMLParser for 'beginning of tags' , 'value of tags' , and then ' end of tags '  

Same is the procedure we are going to follow  and show it in a UITableViewController

The Code

we get a xml file called "articles.xml" and put it in our resource folder.


Now , make a url for the article.xml file which is in the bundle.
We make an object of NSXmlParser and pass the url to it, and dont forget to add the NSXmlParserDelegate , it provides the required methods . We do this thing in our readXml function


As soon as parse is called , the delegate methods are called one by one depending on the tags that appear in the xml file

-first 'didStartElement' function is called  ,where we create a new dictionary object on the beginning of 'article' Element and we create a string on the
beginning of 'title' and 'description' elements


-then 'foundCharacters' function is called , where store the characters in a string


-and then 'didEndElement' function is called , where the string is added to the dictionary on the end 'title' and 'description' tag and dictionary object is added to the array on the end of 'article' tag and



This is repeated for each tag found in the xml file

Now we display this results of parsing in the subclass 'BooksTableViewController' of UITableViewController
 and call the readXml method in its initWithStyle method

An object is made of this BooksTableViewController is called in the appDelegate.m as follows 


And Here we get our final result , Hurray !!!!! You <Parsed> XML !!!!!!

                                                                                         
                                                                                  
 Thanks Friends !!!


P.S. :- I have changed some changes in the xml file , thats why we are getting different results . I have added "Photography","Sports" and "Music" as 'title' in each article and also  added some 'description' to it ...haha !!