Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary to XML

I'm trying to convert a NSDictionary to XML. (I was successful in transforming NSDictionary to JSON). But now I need to transform NSDictionary to XML. Is there a built-in serializer in Objective-C like the one for JSON?

int r = arc4random() % 999999999;

//simulate my NSDictionary (to be turned into xml)
NSString *name = [NSString stringWithFormat:@"Posted using iPhone_%d", r];
NSString *stock_no = [NSString stringWithFormat:@"2342_%d", r];
NSString *retail_price = @"12345";

NSArray *keys = [NSArray arrayWithObjects:@"name", @"stock_no", @"retail_price", nil];
NSArray *objects = [NSArray arrayWithObjects:name,stock_no,retail_price, nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSDictionary *theFinalRequestDictionary = [NSDictionary dictionaryWithObject:theRequestDictionary forKey:@"product"];

...//other irrelevant code omitted

NSData *theBodyData = [NSPropertyListSerialization dataFromPropertyList:theFinalRequestDictionary format:NSPropertyListXMLFormat_v1_0   errorDescription:nil];
NSPropertyListFormat format;

id XMLed = [NSPropertyListSerialization propertyListFromData:theBodyData
                                            mutabilityOption:NSPropertyListImmutable
                                                      format:&format
                                            errorDescription:nil];

NSLog(@"the XMLed is this: %@", [NSString stringWithFormat:@"%@", XMLed]);

The NSLog doesn't print a string in XML format. It prints it like a NSDictionary. What should I use to serialize my NSDictionary to XML?

like image 532
acecapades Avatar asked Nov 04 '22 06:11

acecapades


1 Answers

propertyListFromData:... returns a "property list object", that is, depending on the contents of the data, an array or a dictionary. The thing that you're actually interested in (the xml) is returned by dataFromPropertyList:... and thus stored in your theBodyData variable.

Try this:

NSLog(@"XML: %@", [[[NSString alloc] initWithData:theBodyData encoding:NSUTF8StringEncoding] autorelease]);
like image 69
omz Avatar answered Nov 09 '22 15:11

omz