开发者

Objective-C Parsing XML File

I followed a quick tutorial on parsing an XML file, thi开发者_开发知识库s what i have.

- (void)loadDataFromXML {

    NSString* path = @"/Users/samichaudry/Music/iTunes/iTunes Music Library.xml";

    NSData* data = [NSData dataWithContentsOfFile: path];
    NSXMLParser* parser = [[NSXMLParser alloc] initWithData: data];

    [parser setDelegate:self];
    [parser parse];
    [parser release];
}

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

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

        NSString* name = [attributeDict valueForKey:@"name"];    
        NSString* artist = [attributeDict valueForKey:@"artist"];    
        NSLog(@"Name: %@, Artisit: %@", name, artist);
    }
}

But in the log all i get is this about 60 times;

2011-02-14 22:53:37.617 SearchLibrary[5218:a0f] Name: (null), Artisit: (null)

Can anyone help? Thanks, Sami.


The attribute dict is not what you're looking for.

If you have the XML tag:

<dict foo="bar" baz="42">

Then in the parser:didStartElement:... callback:

  • elementName will be dict
  • attributeDict will be a dictionary with 2 key-value pairs: "foo" => "bar" and "baz" => "42"

Since you're parsing an xml file in plist format, the <dict> does not have any attributes. Therefore, the attributesDict is empty, and [attributesDict objectForKey:@"name"] returns nil.

The absolute simplest way to parse the iTunes xml file is:

NSDictionary *contents = [NSDictionary dictionaryWithContentsOfFile:path];

Keep in mind, however, that this can end up eating a metric ton of memory and totally kill the performance of your app.

But hey, the library will be loaded. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜