将NSDictionary转换成XML

5

我正在尝试将NSDictionary转换为XML。(我已经成功地将NSDictionary转换为JSON)。但现在我需要将NSDictionary转换为XML。Objective-C中是否有像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"];

抱歉,我无法处理您的请求。 我们的服务目前仅支持英语到其他语言的翻译。
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]);

NSLog不能以XML格式打印字符串,它会像一个NSDictionary一样打印。那我应该使用什么来将我的NSDictionary序列化为XML呢?


我猜应该有更简单的方式吧?因为Objective-C内置了JSON序列化器。 - acecapades
2个回答

2

propertyListFromData:...返回一个"属性列表对象",具体取决于数据的内容,可能是数组或字典。你真正感兴趣的东西(xml)由dataFromPropertyList:...返回,并存储在你的theBodyData变量中。

尝试这个:

NSLog(@"XML: %@", [[[NSString alloc] initWithData:theBodyData encoding:NSUTF8StringEncoding] autorelease]);

如何使用NSLog来验证theBodyData是否实际上是XML格式?谢谢! - acecapades

0

XML 有很多不同的种类。如果你不关心具体的标签,并且如果你的字典内容仅限于属性列表中使用的类型(如 NSString、NSNumber、NSDate 等),那么你可以在一行中将字典写入属性列表:

[myDict writeToFile:somePath atomically:YES];

如果您希望将XML保留在内存中而不是写入文件,请像您正在做的那样使用NSPropertyListSerialization。

但是当我使用NSLog打印时,似乎无法将其转换为xml。我的NSPropertyListSerialization语法是否正确? - acecapades

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接