代码之家  ›  专栏  ›  技术社区  ›  TalkingCode

Cocoa/Objective-C:解析XML文档的最佳实践?

  •  1
  • TalkingCode  · 技术社区  · 15 年前

    我以前从未在Cocoa中使用过XML,所以我不知道从哪里开始。

    我的XML看起来像这样

    <Person>
       <FirstName>
       <LastName>
       etc...
    </Person>
    <Person>
    ...
    

    在我的项目中,我已经有一个Person类具有必需的属性。从这样的XML文件创建对象的最佳实践是什么?

    1 回复  |  直到 15 年前
        1
  •  1
  •   Peter Hosey    15 年前

    http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/XMLParsing/Articles/UsingParser.html#//apple_ref/doc/uid/20002264-BCIIJEEH

    正在打开文件:

    - (void)openXMLFile {
        NSArray *fileTypes = [NSArray arrayWithObject:@"xml"];
        NSOpenPanel *oPanel = [NSOpenPanel openPanel];
    
        NSString *startingDir = [[NSUserDefaults standardUserDefaults] objectForKey:@"StartingDirectory"];
        if (!startingDir)
            startingDir = NSHomeDirectory();
    
        [oPanel setAllowsMultipleSelection:NO];
        [oPanel beginSheetForDirectory:startingDir file:nil types:fileTypes
          modalForWindow:[self window] modalDelegate:self
          didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:)
          contextInfo:nil];
    }
    
    - (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
        NSString *pathToFile = nil;
        if (returnCode == NSOKButton) {
            pathToFile = [[[sheet filenames] objectAtIndex:0] copy];
        }
    
        if (pathToFile) {
            NSString *startingDir = [pathToFile stringByDeletingLastPathComponent];
            [[NSUserDefaults standardUserDefaults] setObject:startingDir forKey:@"StartingDirectory"];
    
            [self parseXMLFile:pathToFile];
        }
    }
    

    - (void)parseXMLFile:(NSString *)pathToFile {
        BOOL success;
    
        NSURL *xmlURL = [NSURL fileURLWithPath:pathToFile];
    
        if (addressParser) // addressParser is an NSXMLParser instance variable
            [addressParser release];
    
        addressParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
        [addressParser setDelegate:self];
        [addressParser setShouldResolveExternalEntities:YES];
    
        success = [addressParser parse]; // return value not used
                    // if not successful, delegate is informed of error
    }