2013-08-29 68 views
2

在包中,我連接到外部文件夾,該文件夾是藍色,而不是通常的黃色。 在這個文件夾中有一個xml文件,我必須從中讀取內容。在應用程序中讀取本地xml文件iOS

這是我從中得出「ID」的值的XML文件:

<?xml version='1.0' encoding='UTF-8'?> 
    <root> 
    <event id="2"></event> 
    </root> 

這是我的代碼:在Xcode

- (void)viewDidLoad 
{ 


    NSString *pathFile = [[NSBundle mainBundle] bundlePath]; 
    NSString *path = [[NSString alloc] initWithString:[pathFile stringByAppendingPathComponent:@"config.xml"]]; 
    NSURL *xmlURL = [NSURL fileURLWithPath:path]; 
    NSXMLParser *parser = [[ NSXMLParser alloc] initWithContentsOfURL:xmlURL]; 
    NSLog(@"the parser xml is %@", parser); 

    //the parser xml is <NSXMLParser: 0x967d870> 

    [parser setDelegate:self]; 

    BOOL success = [parser parse]; 

    if(success == YES){ 

     NSLog(@"success"); 
    } else { 

     NSLog(@" not success"); //is not success, why? 
    } 

[parser release]; 
} 


- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict { 

    //in this method does not enter 

    if ([elementName isEqualToString:@"event"]){ 

     NSLog(@" %@", elementName); 

    } 

} 
+0

如果'[解析器解析]'失敗的話,你可以打印'[解析器parserError]'來獲取有關的一些信息失敗。 –

+0

我得到像錯誤:(NSXMLParserErrorDomain錯誤5)。 –

回答

4

藍色文件夾顯示在您的應用程序的實際文件夾束。這意味着你需要在你的代碼中的文件路徑的文件夾名稱:

NSString *bundlePath = [[NSBundle mainBundle] bundlePath]; 
NSString *folderPath = [bundlePath stringByAppendingPathComponent:@"folderName"]; 
NSString *path = [folderPath stringByAppendingPathComponent:@"config.xml"]; 

替換folderName與您的文件夾的實際名稱。

或者,你可以這樣做:

NSURL *xmlURL = [[NSBundle mainBundle] URLForResource:@"config" withExtension:@"xml" subdirectory:@"folderName"]; 
1

試試這個:

NSString *configFileURL = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"XMLFileName"]; 

    NSDictionary *settingsDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] 
    pathForResource:configFileURL ofType:@"xml"]]; 
相關問題