October 2013
Intermediate to advanced
1053 pages
28h 7m
English
You want to parse an XML snippet or document.
Use the NSXMLParser
class.
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><personid="1"><firstName>Anthony</firstName><lastName>Robbins</lastName><age>51</age></person><personid="2"><firstName>Richard</firstName><lastName>Branson</lastName><age>61</age></person></root>
Now define a property of type NSXMLParser:
#import "AppDelegate.h"@interfaceAppDelegate()<NSXMLParserDelegate>@property(nonatomic,strong)NSXMLParser*xmlParser;@end@implementationAppDelegate
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. Now let’s read the MyXML.xml file from the disk and pass it to
your XML parser:
-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions{NSString*xmlFilePath=[[NSBundlemainBundle]pathForResource:@"MyXML"ofType:@"xml"];NSData*xml=[[NSDataalloc]initWithContentsOfFile:xmlFilePath];self.xmlParser=[[NSXMLParseralloc]initWithData:xml];self.xmlParser.delegate=self;if([self.xmlParserparse]){NSLog(@"The XML is parsed.");}else{NSLog(@"Failed to parse the ...
Read now
Unlock full access