Search code examples
iphoneiosxmlnsxmlparserentities

iphone : NSXMLParser fails to identify HTML special entity &


I simply cannot get NSXMLParser to recognize &

here is my XML:

 <?xml version="1.1" encoding="UTF-8"?>
 <root>
     <myURL>http://www.mywebsite.com/info?id=32&amp;page=5</myURL>>
 </root>

Here is my parsing code:

-(void)getXml {
 NSURL *xmlurl = [[NSURL alloc] initWithString:@"http://www.mywebsite.com/myxml.xml"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlurl];
[xmlParser setDelegate:self];
[xmlParser parse];
[xmlParser release];
[dataurl release];
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {

NSLog(@"Parser Error: %@", parseError);

}

 - (void)parser:(NSXMLParser *)parser validationErrorOccurred:(NSError *)validError {

NSLog(@"Parser validation Error: %@", validError);


}


- (void)parserDidStartDocument:(NSXMLParser *)parser {

NSLog(@"Parser started");


}

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

NSLog(@"Found key: %@", elementName);


}

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

NSLog(@"Found Element: %@", string);


}


- (void)parserDidEndDocument:(NSXMLParser *)parser {

NSLog("done"):

}

Here is my output:

 Found key: root
 Found key: myURL
 Found element: http://www.mywebsite.com/info?id=32
 Found element: page=5
 Found element: 
 Found key: myURL

The parser is not recognizing the & correctly and is splitting up my url. I have seen many Stack questions on this issue but none of them have helped and I have read the Apple docs on NSXMLParser as well. Am I missing something here?

I am building with iOS 5.0 to an iPhone 4


Solution

  • According to the NSXMLParserDelegate documentation:

    The parser object may send the delegate several parser:foundCharacters: messages to report the characters of an element. Because string may be only part of the total character content for the current element, you should append it to the current accumulation of characters until the element changes.

    So the usual pattern of usage is to keep appending to a temporary string until the end of the element is reached:

    .h

    @property (nonatomic,retain) NSMutableString *tempString;
    

    .m

    @synthesize tempString;
    
    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI  qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
    {
        self.tempString = @"";
    }
    
    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
    {
        [self.tempString appendString:string];
    }
    
    - (void)parserDidEndDocument:(NSXMLParser *)parser
    {
        // do something with self.tempString
    }