开发者

Cocoa/Objective-C : Best Practice to parse XML Document?

I never worked with XML in Cocoa before so I have no idea where to begin. Right now I need to parse a XML File (from Hard disc) into an object or even an Array of objects.

My XML looks like this

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

In my project I already ha开发者_如何学编程ve a Person class with a required properties. What is the best practice to create objects from such XML file?


Hope this helps.

Please take a look at:

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

Opening File:

- (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];
    }
}

Parse:

- (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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜