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

前端 未结 1 1884
情话喂你
情话喂你 2020-11-27 08:23

I 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         


        
相关标签:
1条回答
  • 2020-11-27 08:36

    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

    0 讨论(0)
提交回复
热议问题