NSXMLParser used to Decode XML

One problem I found was that when I was receiving encoded XML from a webservice I would need to decode it so I could use it.  What I ended up doing was just running it through the NSXMLParser and building it into a new XML doc that I will dispose of when finished. It’s pretty simple and saves me a nuch of time.  This will also decode any form of tagged language so XHTML will go as well.

//HTMLDecoder.h

#import <Foundation/Foundation.h>

@interface HTMLDecoder : NSObject {
NSMutableString* sDecodedString;
}

@property (nonatomic, retain) NSMutableString* sDecodedString;
- (NSString*)convertEntiesInString:(NSString*)s;

@end

// ************************************************************************************** //

// ************************************************************************************** //

//HTMLDecoder.m
#import “HTMLDecoder.h”

@implementation HTMLDecoder

@synthesize sDecodedString;

// ************************************************************************************** //

-(void) dealloc
{
[sDecodedString release];
[super dealloc];
}

// ************************************************************************************** //

-(id) init
{
if( [super init])
{
sDecodedString = [[NSMutableString alloc] init];
}
return self;
}

// ************************************************************************************** //

- (void) parser:(NSXMLParser *) parser foundCharacters:(NSString *) s
{
[self.sDecodedString appendString:s];
}

// ************************************************************************************** //

- (NSString*) convertEntiesInString:(NSString*) s
{
NSString*    sXML     = [NSString alloc] initWithFormat:@”<xml>%@</xml>”, s];
NSData*      dataXML  = [sXML dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSXMLParser* parseXML = [[NSXMLParser alloc] initWithData:dataXML];
[parseXML setDelegate:self];
[parseXML parse];

NSString* sRetVal = [[NSString alloc] initWithFormat:@”%@”, sDecodedString];
[sXML release];
[parseXML release];
return [sRetVal autorelease];
}

// ************************************************************************************** //

@end