2010-02-10 28 views
1

我從來沒有在可可中使用過XML,所以我不知道從哪裏開始。 現在我需要解析一個XML文件(從硬盤)到一個對象甚至一個對象數組中。Cocoa/Objective-C:解析XML文檔的最佳實踐?

我的XML看起來像這樣

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

在我的項目,我已經有一個需要的屬性Person類。從這種XML文件創建對象的最佳做法是什麼?

回答

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 
}