实现把字典转换为XML数据

实现把字典转换为XML数据:

[objc]  view plain  copy
  1. #pragma mark - 字典转换为XML字符串  
  2. - (NSString *)convertDictionaryToXML:(NSMutableDictionary *)dictionary withStartElement:(NSString *)startElement  
  3. {  
  4.     return [self convertDictionaryToXML:dictionary withStartElement:startElement isFirstElement:YES];  
  5. }  
  6.   
  7. - (NSString *)convertDictionaryToXML:(NSMutableDictionary *)dictionary withStartElement:(NSString *)startElement isFirstElement:(BOOL) isFirstElement  
  8. {  
  9.     NSMutableString *xml = [[NSMutableString alloc] initWithString:@""];  
  10.     NSArray *allKeysArr = [dictionary allKeys];  
  11.     [xml appendString:startElement];  
  12.       
  13.     for(int i = 0; i < allKeysArr.count; i++){  
  14.         NSString *nodeName = [allKeysArr objectAtIndex:i];  
  15.         id nodeValue = [dictionary objectForKey:nodeName];  
  16.           
  17.         if([nodeValue isKindOfClass:[NSArray class]]){  
  18.             if([nodeValue count] > 0){  
  19.                 for(int j = 0;j < [nodeValue count]; j++){  
  20.                     id value = [nodeValue objectAtIndex:j];  
  21.                     if([value isKindOfClass:[NSDictionary class]]){  
  22.                         [xml appendString:[self convertDictionaryToXML:value withStartElement:nodeName isFirstElement:NO]];  
  23.                     }  
  24.                 }  
  25.             }  
  26.         }else if([nodeValue isKindOfClass:[NSDictionary class]]){  
  27.             [xml appendString:[self convertDictionaryToXML:nodeValue withStartElement:nodeName isFirstElement:NO]];  
  28.         }else{  
  29.             if([nodeValue length] > 0){  
  30.                 [xml appendString:[NSString stringWithFormat:@"<%@>",nodeName]];  
  31.                 [xml appendString:[NSString stringWithFormat:@"%@",[dictionary objectForKey:nodeName]]];  
  32.                 [xml appendString:[NSString stringWithFormat:@"</%@>",nodeName]];  
  33.             }  
  34.         }  
  35.     }  
  36.       
  37.     [xml appendString:[NSString stringWithFormat:@"</TVUMetaData>"]];  
  38.     NSString *finalxml = [xml stringByReplacingOccurrencesOfString:@"&" withString:@"&"];  
  39.     return finalxml;  
  40. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值