无法使用NSXMLParser解析XML

时间:2012-02-27 12:19:56

标签: ios xml xcode nsxmlparser

我有一个iOS应用程序。所有数据都存储在xml文件中。

<?xml version="1.0" encoding="utf-8"?>
<objects>
    <object 
        name="Скульптура Р. Исмагилова «Пермяк – соленые уши»" 
        xcoord="58.00998487478568" 
        ycoord="56.239829063415527"
        type="" 
        description="" 
        external_name="gl1" />
</objects>

所以,我想将这个XML文件解析为NSMutableArray

我使用NSXMLParser删除类来实现。这是班级代码:

@implementation XMLParser

@synthesize aPLace;

- (XMLParser *) initXMLParser {

    [super init];

    appDelegate = (XMLAppDelegate *)[[UIApplication sharedApplication] delegate];

    return self;
}

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

    NSLog(@"parsing");

    if([elementName isEqualToString:@"objects"]) {
        //Initialize the array.
        appDelegate.books = [[NSMutableArray alloc] init];
    }
    else if([elementName isEqualToString:@"object"]) {

        //Initialize the book.
        aPLace = [[Place alloc] init];

        //Extract the attribute here.
        aPLace.name = [[attributeDict objectForKey:@"name"] string];

        NSLog(@"Reading name :%@", aPLace.name);
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 

}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

    if([elementName isEqualToString:@"objects"])
        return;

    if([elementName isEqualToString:@"object"]) {
        [appDelegate.greenLine addObject:aPLace];
    }

}

@end

您可以看到NSLog(@"parsing");功能中有didStartElement。但输出是空的。

所以,我在AppDelegateClass's函数applicationDidFinishLaunching

中实现解析
- (void)applicationDidFinishLaunching:(UIApplication *)application {


    NSURL *url = [[NSURL alloc] initWithString:@"greenline_ru.xml"];
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];

    //Initialize the delegate.
    XMLParser *parser = [[XMLParser alloc] initXMLParser];

    //Set delegate
    [xmlParser setDelegate:parser];

    //Start parsing the XML file.
    BOOL success = [xmlParser parse];

    if(success)
        NSLog(@"No Errors");
    else
        NSLog(@"Error Error Error!!!");

    // Configure and show the window
    [window addSubview:[navigationController view]];
    [window makeKeyAndVisible];
}

每次输出Error Error Error!!!为什么?有什么问题?

2 个答案:

答案 0 :(得分:2)

NSURL *url = [[NSURL alloc] initWithString:@"greenline_ru.xml"];

我认为这是你的问题。如果你有文件,你应该使用像

这样的东西
NSString *path = [[NSBundle mainBundle] pathForResource:@"greenline_ru"
                                                 ofType:@"xml"];
[[NSXMLParser alloc] initWithData:[NSData dataWithContentsOfFile:path]]

答案 1 :(得分:0)

使用TBXML,这很容易使用...... 研究这个 - http://www.tbxml.co.uk/TBXML/API.html