2011-02-14 53 views
2

我需要一些幫助我想加載一個XML文件到表視圖這是我到目前爲止,任何人都可以向我解釋如何做到這一點。我認爲它也會涉及到綁定,我知道這一點。Objective-C使用NSDictionary的實例填充表視圖

NSString* libraryPath = @"~/Music/iTunes/iTunes Music Library.xml"; 
NSDictionary* musicLibrary = [ NSDictionary dictionaryWithContentsOfFile: libraryPath ]; 

謝謝,薩米。

回答

1

您可以使用NSXMLDocument來解析XML文件,它可能比執行NSXMLParser.更容易一些。下面是一個示例(未經測試)。

- (void) parseItunesLibrary { 
    NSError* error = nil; 
    NSString* libraryPath = nil; 

    // better way to get the iTunes database file (in case library was moved) 
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; 
    NSDictionary* iAppsDict = [defaults persistentDomainForName:@"com.apple.iApps"]; 
    NSArray* itunesDBPath = [iAppsDict objectForKey:@"iTunesRecentDatabasePaths"]; 
    if([itunesDBPath count] > 0) { 
     libraryPath = [[itunesDBPath objectAtIndex: 0] stringByExpandingTildeInPath]; 
    } 

    NSData* libraryData = [NSData dataWithContentsOfFile:libraryPath]; 
    NSXMLDocument* libraryDoc = [[NSXMLDocument alloc] initWithData:libraryData options:NSXMLDocumentTidyXML error:&error]; 
    // handle error before continuing here 
    if (error) { 
     NSLog(@"%@", [error localizedDescription]); 
     [libraryDoc release]; 
     return; 
    } 

    NSXMLElement* root = [libraryDoc rootElement]; 
    [libraryDoc release]; 

    // assuming you wanted an array of the songs you can get them like this 
    NSArray* songsArray = [root nodesForXPath:@".//dict/dict/dict" error:nil]; 

    // to access the different song elements you can do something like this 
    for(NSXMLElement* song in songsArray) { 
     NSString* songArtist = [[[song nodesForXPath:@"./Artist" error:nil] lastObject] stringValue]; 
    } 
} 

一旦你有了這個數據,你可以把它放在一個NSTableView你喜歡的任何方式。看看在NSTableView Programming Guide中使用表數據源。

+0

只是想知道,你有沒有想過去測試這個? – 2012-04-19 22:33:20