NSXMLParser Simple Example

后端 未结 4 576
说谎
说谎 2020-12-24 10:50

Most of the examples of how to invoke the NSXMLParser are contained within complex projects involving Apps. What does a simple example that demonstrates the callbacks look l

4条回答
  •  -上瘾入骨i
    2020-12-24 11:25

    As part of exploring the NSXMLParser I created the following really simple code.

    main.m

    int main(int argc, const char * argv[])
    {
    
        @autoreleasepool {
            NSLog(@"Main Started");
    
            NSError *error = nil;
    
            // Load the file and check the result
            NSData *data = [NSData dataWithContentsOfFile:@"/Users/Tim/Documents/MusicXml/Small.xml"
                                              options:NSDataReadingUncached
                                                error:&error];
            if(error) {
                NSLog(@"Error %@", error);
    
                return 1;
            }
    
    
            // Create a parser and point it at the NSData object containing the file we just loaded
            NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    
            // Create an instance of our parser delegate and assign it to the parser
            MyXmlParserDelegate *parserDelegate = [[MyXmlParserDelegate alloc] init];
            [parser setDelegate:parserDelegate];
    
            // Invoke the parser and check the result
            [parser parse];
            error = [parser parserError];
            if(error)
            {
                NSLog(@"Error %@", error);
    
                return 1;
            }
    
            // All done
            NSLog(@"Main Ended");
        }
        return 0;
    }
    

    MyXmlParserDelegate.h

    #import 
    
    @interface MyXmlParserDelegate : NSObject 
    
    @end
    

    MyXmlParserDelegate.m

    #import "MyXmlParserDelegate.h"
    
    @implementation MyXmlParserDelegate
    
    - (void) parserDidStartDocument:(NSXMLParser *)parser {
        NSLog(@"parserDidStartDocument");
    }
    
    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
        NSLog(@"didStartElement --> %@", elementName);
    }
    
    -(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
        NSLog(@"foundCharacters --> %@", string);
    }
    
    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
        NSLog(@"didEndElement   --> %@", elementName);
    }
    
    - (void) parserDidEndDocument:(NSXMLParser *)parser {
        NSLog(@"parserDidEndDocument");
    }
    @end
    

    I've posted it in the hope that it helps someone else.

提交回复
热议问题