NSXMLParser on iOS, how do I use it given a xml file

The simplest thing is to do something like this:

NSXMLParser *xmlParser = [[NSXMLParser alloc]initWithData:<yourNSData>];
[xmlParser setDelegate:self];
[xmlParser parse];

Notice that setDelegate: is setting the delegate to ‘self’, meaning the current object. So, in that object you need to implement the delegate methods you mention in the question.

so further down in your code, paste in:

    - (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
        namespaceURI:(NSString *)namespaceURI
       qualifiedName:(NSString *)qualifiedName 
         attributes:(NSDictionary *)attributeDict{

       NSLog(@"I just found a start tag for %@",elementName);
       if ([elementName isEqualToString:@"employee"]){
       // then the parser has just seen an <employee> opening tag
       }         
     }

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
NSLog(@"the parser just found this text in a tag:%@",string);
}

etc. etc.

It’s a little harder when you want to do something like set a variable to the value of some tag, but generally it’s done using a class variable caleld something like “BOOL inEmployeeTag” which you set to true (YES) in the didStartElement: method and false in the didEndElement: method – and then check for it’s value in the foundCharacters method. If it’s yes, then you assign the var to the value of string, and if not you don’t.

richard

Leave a Comment