NSXMLParser on iOS, how do I use it with an XML file

I was wondering how I can use the NSXML parser. so to say, given that I have a simple XML file with elements such as:

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

How can I use NSXMLParser to parse an XML file (it is located locally, for example, on the desktop), check each element and save each of them in an array that will be displayed / used later?

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

+3
source share
1 answer

The simplest thing is to do something like this:

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

Note that setDelegate: sets the delegate to "self", which means the current object. So, in this object you need to implement the delegate methods that you mentioned in the question.

so on in your code, insert:

  - (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 .. and others.

This is a bit more complicated if you want to do something like setting a variable to the value of a tag, but this is usually done using a caleld class variable, for example, " BOOL inEmployeeTag ", which you set to true (YES) in the didStartElement : method and false in the didEndElement : method - and then check its value in the foundCharacters method. If so, then you assign var to the value of the string, and if not, then no.

Richard

+4
source

All Articles