Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSXMLParser init with XML in NSString format

I just ran into this one and couldn't seem to get any clear answer from the documentation.

Im retrieving some XML through a HTTPS connection. I do all sorts of authentication etc. so I have a set of classes that deals with this in a nice threaded way. The result is an NSString that goes something like:

<response>
//some XML formatted test
</response>

This means that there is no encoding="UTF-8" indent="yes" method="xml" or other header blocks to indicate that this is actual XML and not just an NSString.

I guess I will use [NSXMLParser initWithData:NSData] to construct the parser, but how will I format or cast my NSString of xml formatted text into a proper NSData object that NSXMLParser will understand and parse?

Hope it makes sense, thank you for any help given :)

like image 525
RickiG Avatar asked Dec 03 '09 16:12

RickiG


Video Answer


2 Answers

You can convert a string to a NSData object using the dataUsingEncoding method:

NSData *data = [myString dataUsingEncoding:NSUTF8StringEncoding];

You can then feed this to NSXMLParser.

like image 129
Philippe Leybaert Avatar answered Nov 03 '22 00:11

Philippe Leybaert


The headers are optional, but you can insert the appropriate headers yourself if needed:

NSString *header = @"<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
NSString *xml = [NSString stringWithFormat:@"%@\n%@", header, response);
NSData *data = [xml dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *praser = [NSXMLParser initWithData:data];
like image 34
notnoop Avatar answered Nov 02 '22 23:11

notnoop