1

I followed a quick tutorial on parsing an XML file, this 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.

1 Answer 1

3

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. :)

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, yeah that makes sense, can you help me i want to write an app with a search field, button and table view, when the user types a string into the search field and presses the button the button calls a method to search through the iTunes Music Library.xml file for the string in either the track's name or track's artist's name and display the results in the tableview. Could you tell me how to do it or possibly do it for me if you have time? I know it's much to ask but i'm really stuck, thanks Dave.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.