加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

iphone – NSDictionary到XML

发布时间:2020-12-14 19:13:24 所属栏目:百科 来源:网络整理
导读:我正在尝试将NSDictionary转换为 XML. (我成功地将NSDictionary转换为 JSON).但现在我需要将NSDictionary转换为XML.在Objective-C中是否有类似JSON的内置序列化程序? int r = arc4random() % 999999999;//simulate my NSDictionary (to be turned into xml)
我正在尝试将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?

解决方法

propertyListFromData:…返回“属性列表对象”,即根据数据的内容,数组或字典.你真正感兴趣的东西(xml)由dataFromPropertyList:…返回,因此存储在你的theBodyData变量中.

试试这个:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读