2011-10-21 86 views
0

我是Iphone開發新手,我在本地保存了一個xml文件,並使用NSXmlParser(存儲在Resource文件夾中)顯示細節。但是,現在我想從url(從客戶端)下載新的xml,並需要將該新的xml文件存儲在Cache目錄中,並且還要從資源文件夾中刪除xml文件。但我沒有解析緩存目錄中的新XML文件,我如何解析緩存目錄中的新XML文件?任何人都知道這一點,請幫助我如何從Cachedirectory檢索Xml文件?

回答

0

我其實剛剛爲我的一個項目寫了這個功能。我將分享我用來保存和寫入XML文件到我的緩存中的代碼。

- (NSString *)XMLCacheFilePath 
{ 
    NSString *directory = @"/Library/Caches/XML/"; 
    NSString *fileName = [@"file" stringByAppendingPathExtension:@"xml"]; 

    // Setup directory path 
    NSString *homeDirectoryPath = NSHomeDirectory(); 
    NSString *unexpandedDirectoryPath = [homeDirectoryPath stringByAppendingString:directory]; 
    NSString *directoryPath = [NSString pathWithComponents:[NSArray arrayWithObjects: 
                 [NSString stringWithString:[unexpandedDirectoryPath stringByExpandingTildeInPath]], 
                 nil]]; 

    // Setup file path 
    NSString *unexpandedFilePath = [directoryPath stringByAppendingPathComponent:fileName]; 
    NSString *filePath = [NSString pathWithComponents:[NSArray arrayWithObjects: 
                 [NSString stringWithString:[unexpandedFilePath stringByExpandingTildeInPath]], 
                 nil]]; 

    if (![[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:nil]) { 
     NSError *error = [[NSError alloc] init]; 

     [[NSFileManager defaultManager] createDirectoryAtPath:directoryPath 
           withIntermediateDirectories:YES 
               attributes:nil 
                error:&error];     
    } 

    return filePath; 
} 

- (void)saveXMLStringToDisk:(NSString *)xmlString 
{ 
    NSError *error; 

    [xmlString writeToFile:self.XMLCacheFilePath 
       atomically:YES 
        encoding:NSUTF8StringEncoding 
        error:&error]; 
} 

- (NSString *)XMLStringFromDisk 
{ 
    NSString *XMLString = [NSString stringWithContentsOfFile:self.XMLCacheFilePath 
                encoding:NSUTF8StringEncoding 
                 error:nil]; 

    return XMLString; 
}