NSXMLParser init with XML in NSString format NSXMLParser init with XML in NSString format xml xml

NSXMLParser init with XML in NSString format


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.


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];


By the time NSXMLParser has the data it's pretty much going to be expecting it to be XML ;-)

I'm pretty sure the processing instruction header is optional in this context. The way you get the NSString into the NSData is going to dictate the encoding (using dataUsingEncoding:).

(edit: I was looking for the encoding enum, but Philippe Leybaert beat me to it, but to repeat it here anyway, something like: [nsString dataUsingEncoding:NSUTF8StringEncoding])

I've passed NSStrings of XML in this way before with no issues.

Not specific to this question as such, but on the subject of XML parsing in an iPhone context in general you may find this blog entry of mine interesting, too.