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

I was wondering how do I use the NSXML parser. so lets say given I have a simple xml file with elements like:

<Today>
<Date>1/1/1000</Date>
<Time>14:15:16</Time>
</Today>

How could I use the NSXMLParser to parse the XML File (It's on locally btw, desktop), check through each element and store each of them in an array either to be displayed/used later?

I was looking through some documentation about it and I have no idea on how to use the parser I know that there are 3 methods (or more, please correct me if I'm wrong) that can be overridden -..etc didStartElement -..etc didEndElement -..etc foundCharacters


Solution 1:

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