2013-08-29 48 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"]]; 
相关问题