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

时间:2010-02-10 15:06:12

标签: objective-c xml cocoa

之前我从未使用过Cocoa中的XML,所以我不知道从哪里开始。 现在我需要将XML文件(从硬盘)解析为对象甚至是对象数组。

我的XML看起来像这样

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

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

1 个答案:

答案 0 :(得分:1)

希望这有帮助。

请看一下:

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
}