Simple and concise desktop Cocoa NSXMLParser example?

后端 未结 3 1618
梦如初夏
梦如初夏 2021-01-25 07:54

I would like to look through the elements of a file and when one specific element comes out, output the contents in between the tag.

I tried to follow the example in the

3条回答
  •  爱一瞬间的悲伤
    2021-01-25 08:33

    This is based on something I originally wrote for Cut out a part of a long NSString. I copied the NSXMLParserDelegate code from that iOS project into an OS X project. It gets the text from a specific object in a web page.

    .h file:

    @interface so7576593AppDelegate : NSObject  {
        NSWindow *window;
        IBOutlet NSTextField *textField;
    
        NSMutableString *divCharacters;
        BOOL captureCharacters; 
    }
    
    @property (assign) IBOutlet NSWindow *window;
    
    @end
    

    .m file:

    #import "so7576593AppDelegate.h"
    
    @implementation so7576593AppDelegate
    
    @synthesize window;
    
    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        captureCharacters = NO;
        NSURL *theURL = [NSURL URLWithString:@"http://maxnerios.yolasite.com/"];
        NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:theURL];
        [parser setDelegate:self];
        [parser parse];
        [parser release];
    
    }
    
    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
        if ([elementName isEqual:@"div"] && [[attributeDict objectForKey:@"id"] isEqual:@"I3_sys_txt"]) {
            captureCharacters = YES;
            divCharacters = [[NSMutableString alloc] initWithCapacity:500];
        }
    }
    
    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
        if (captureCharacters) {
            //from parser:foundCharacters: docs:
            //The parser object may send the delegate several parser:foundCharacters: messages to report the characters of an element. 
            //Because string may be only part of the total character content for the current element, you should append it to the current 
            //accumulation of characters until the element changes.
            [divCharacters appendString:string];
        }
    }
    
    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
        if (captureCharacters) {
            captureCharacters = NO;
            [textField setStringValue:divCharacters];
            [divCharacters release];
        }
    }
    
    @end 
    

提交回复
热议问题