O'Reilly logo

iOS 5 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.12. Parsing XML with NSXMLParser

Problem

You want to parse an XML snippet or document.

Solution

Use the NSXMLParser class.

Discussion

The NSXMLParser uses a delegate model to parse XML content. Let’s go ahead and create a simple XML file that contains the following data (save this file as MyXML.xml in your project):

<?xml version="1.0" encoding="UTF-8"?>
<root>

  <person id="1">
    <firstName>Anthony</firstName>
    <lastName>Robbins</lastName>
    <age>51</age>
  </person>

  <person id="2">
    <firstName>Richard</firstName>
    <lastName>Branson</lastName>
    <age>61</age>
  </person>

</root>

Now define a property of type NSXMLParser:

#import <UIKit/UIKit.h>

@interface Parsing_XML_with_NSXMLParserAppDelegate
           : UIResponder <UIApplicationDelegate, NSXMLParserDelegate>

@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) NSXMLParser *xmlParser;

@end

You can also see that I have defined my app delegate as an XML parser delegate by conforming to the NSXMLParserDelegate protocol, which is required for a delegate object of an XML parser of type NSXMLParser. Let’s continue to synthesize our XML parser:

#import "Parsing_XML_with_NSXMLParserAppDelegate.h"

@implementation Parsing_XML_with_NSXMLParserAppDelegate

@synthesize window = _window;
@synthesize xmlParser;
...

Now read the MyXML.xml file from the disk and pass it to your XML parser:

- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ NSString *xmlFilePath = [[NSBundle mainBundle] pathForResource:@"MyXML" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required