A complete example of parsing an XML file
In the.h file
@interface AppMain : NSObject
<NSXMLParserDelegate> //- ADD THIS DELEGATE
{
NSMutableString *xmlString; //-ADD THIS STRING
In the.m file
//********** PARSE XML FILE **********
- (void) SomeMethodName:(NSData *)file
{
//----- PARSE THE XML -----
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:file];
[parser setDelegate:self];
[parser parse];
//We hold here until the parser finishes execution
[parser release];
}
//***************************************************
//***************************************************
//***** PARSE XML FILE - START ELEMENT CALLBACK *****
//***************************************************
//***************************************************
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)nameSpaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
if (!xmlString)
xmlString = [[NSMutableString alloc] init];
else
[xmlString setString:@""];
if ([elementName isEqual:@"SomeSection"])
{
//----- START OF A NEW #### SECTION -----
//Set up for a new section of values
}
}
//*****************************************************
//*****************************************************
//***** PARSE XML FILE - MORE CHARACTERS CALLBACK *****
//*****************************************************
//*****************************************************
- (void)parser:(NSXMLParser *)parser
foundCharacters:(NSString *)string
{
[xmlString appendString:string];
}
//*************************************************
//*************************************************
//***** PARSE XML FILE - END ELEMENT CALLBACK *****
//*************************************************
//*************************************************
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if ([elementName isEqual:@"SomeElement"])
{
//----- END OF A #### ELEMENT -----
if (![xmlString isEqual:@""])
[SomeArray addObject:xmlString];
}
//Release string
[xmlString release];
xmlString = nil;
}