0

I'm new to Objective C and I am using a helper that returns an XML payload from a web service as an NSXMLParser. I need to get that payload as either an NSString of XML or as an NSData object so that I can use it in another library that converts the payload to an NSDictionary.

Is there an easy way to convert this XML to a string? From the docs, I see that I could write my own string builder using the events of NSXMLParser but this feels like re-inventing the wheel compared to working with XML in other languages.

Rich Tolley
  • 3,812
  • 1
  • 30
  • 39
jvhang
  • 747
  • 6
  • 19
  • 2
    It sounds like maybe you should just bypass the helper and fetch the XML from the web service yourself. – bdesham Feb 15 '13 at 15:50
  • 1
    Do you need to use that particular helper for some reason? The way I'd do it would be to use an `NSURLConnection` - the `NSURLConnectionDelegate` method `-connectionDidReceivedData:` could be implemented so as to append the data to an `NSMutableData` instance - you could then feed that into your other library – Rich Tolley Feb 15 '13 at 15:52
  • Yeah, everyone seems to be saying to skip the library (which is AFXMLRequestOperation). I'll hook that up. I wonder why the library returns a parser rather than a string...oh well. – jvhang Feb 15 '13 at 17:17

2 Answers2

1

Will this work for you?

NSString *googleString = @"http://www.google.com";
NSURL *googleURL = [NSURL URLWithString:googleString];
NSError *error;
NSString *googlePage = [NSString stringWithContentsOfURL:googleURL 
                                                encoding:NSASCIIStringEncoding
                                                   error:&error];

from here Reading HTML content from a UIWebView

From here you should be able to covert to NSXmlParser or NSData but if you make this request to the service it should return the xml as string.

Community
  • 1
  • 1
madmik3
  • 6,975
  • 3
  • 38
  • 60
0

You can convert the NSMutableData to a string:

You send the request:

conexion = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (conexion) {
        webData = [NSMutableData data];
    }

Then you parse the webData to string. In this function: connectionDidFinishLoading

NSString *XML = [[NSString alloc] 
                     initWithBytes: [webData mutableBytes] 
                     length:[webData length] 
                     encoding:NSUTF8StringEncoding];

If you need to display the result

NSLog(@"%@", XML);
jdiego
  • 112
  • 1
  • 8