tags:

views:

127

answers:

1

Hey guys, was wondering how do i use the NSXML parser. so lets say given i have a simple xml file with elements like 1/1/1000 14:15:16

How could i use the NSXMLParser to parse the XML File(Its 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 absolutely have no idea on how to use the parser i know that there are 3 methods(or more ,please correct me if im wrong) that can be overridden -..etc didStartElement -..etc didEndElement -..etc foundCharacters

A: 

Hi, 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

richard