views:

1300

answers:

1

What do I need to do to NSXMLParser so it handles entity characters? For example, if I have the following element <anElement>Left & Right</anElement> I am only getting " Right" in the parser:foundCharacters: delegate method.

Thanks.

+4  A: 

I threw together a really quick prototype application to test this out. What you are describing is not the behavior I'm seeing:

XML File:

<?xml version="1.0" encoding="UTF-8" ?>
<my_element>Left &amp; Right</my_element>

Implementation:

#import "XMLMeController.h"

@implementation XMLMeController

- (IBAction)parse:(id)sender
{
    NSURL *url = [NSURL fileURLWithPath:@"/Users/robertwalker/Desktop/test.xml"];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
    [parser setDelegate:self];
    [parser parse];
    [parser release];
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    NSLog(@"Found: %@", string);
}

@end

Console output:

2008-11-11 20:41:47.805 XMLMe[10941:10b] Found: Left
2008-11-11 20:41:47.807 XMLMe[10941:10b] Found: &
2008-11-11 20:41:47.807 XMLMe[10941:10b] Found: Right

As you can see the parser is finding the "Left" then the "&" and then "Right" as three separate events that are sent to the delegate.

I can't really tell from your posting, but you need to make sure that the proper entity is used in the XML file "&amp;" rather than just "&" character, which of course is invalid in XML files.

Robert Walker
Thanks Robert. I didn't realize the foundCharacters method would be called for each "word" in the element value. So it looks like I just need to append characters to a temporary string that will be used while I'm still in the same element.
Ryan Brubaker
Yes, that's correct. NSXMLParser works at a pretty low level and this is fairly common behavior in XML. The white space is causing there to be multiple text nodes inside the element and NSXMLParser is giving you a chance to deal with each in a separate event.
Robert Walker