iOS中xml的简单构造

先说说需求

有时,在项目中,我们需要将参数以xml字符串的格式发送请求。比如http://192.168.1.1?key="我是xml字符串"

第一步

这里我选择了KissXML(https://github.com/robbiehanson/KissXML) 作为解析xml的第三方库

  • 来看一下我们需要构造的格式
iOS中xml的简单构造_第1张图片
xml_2.png

代码如下
+ (NSString *)commonXMLWithDictionary:(NSDictionary *)dict{

  NSString *xmlStr = nil;
   //构造XML
   //一级
  DDXMLElement *rootElement = [[DDXMLElement alloc]  initWithName:@"request"];
  DDXMLNode *platformNoAttr = [DDXMLNode attributeWithName:@"platformNo" stringValue:@"1001001"];
  [rootElement addAttribute:platformNoAttr];

  for (NSString *key in dict) {
    DDXMLElement *childNode = [[DDXMLElement alloc] initWithName:key stringValue:dict[key]];
    [rootElement addChild:childNode];
}
  xmlStr = [rootElement XMLString];
  return xmlStr;
}

调用时,只要将param放入字典中

新的困难

但如果遇到这样的呢,如下图


iOS中xml的简单构造_第2张图片
xml_3.png

下又有新的子节点出现了,甚至出现多重嵌套的情况,所以我们将以上的函数进行修改,以适应多重嵌套的情况,这里用到了递归的思想

+ (NSString *)commonXMLWithDictionary:(NSDictionary *)dict{

NSString *xmlStr = nil;

//构造XML
//一级
DDXMLElement *rootElement = [[DDXMLElement alloc] initWithName:@"request"];
DDXMLNode *platformNoAttr = [DDXMLNode attributeWithName:@"platformNo" stringValue:@"8888"];
[rootElement addAttribute:platformNoAttr];

[self analysisWithParamBody:dict andRootElement: rootElement];

xmlStr = [rootElement XMLString];

return xmlStr;
}

+ (void)analysisWithParamBody:(NSDictionary *)dict andRootElement:(DDXMLElement *)ele{

for (NSString *key in dict) {
   
    DDXMLElement *childNode = nil;
    
    if ([dict[key] isKindOfClass:[NSDictionary class]]) {
        childNode = [[DDXMLElement alloc] initWithName:key];
      //若子节点中依然包含节点
        [self analysisWithParamBody:dict[key] andRootElement:childNode];
    }else{
        
         childNode = [[DDXMLElement alloc] initWithName:key stringValue:dict[key]];
    }
   
    [ele addChild:childNode];
}
}

注意,对于调用时,字典的构造,应如下

 NSMutableDictionary *param = [NSMutableDictionary dictionary];
 
    [param setObject:@"xxxx" forKey:@"requestNo"];
    [param setObject:@"xxxx" forKey:@"platformUserNo"];
    [param setObject:@"xxxx" forKey:@"amount"];
    [param setObject:@"xxxx" forKey:@"feeMode"];
    [param setObject:@"xxxx" forKey:@"callbackUrl"];
    [param setObject:@"xxxx" forKey:@"notifyUrl"];

多重嵌套时,字典的构造,如下

NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setObject:@"xxxx" forKey:@"requestNo"];
    [param setObject:@"xxxx" forKey:@"platformUserNo"];
    [param setObject:@"xxxx" forKey:@"userType"];

    //<---detail-->
    NSMutableDictionary *subDict = [NSMutableDictionary dictionary];
    [subDict setObject:@"xxxx" forKey:@"amount"];
    [subDict setObject:@"xxxx" forKey:@"targetUserType"];
    [subDict setObject:@"xxxx"forKey:@"targetPlatformUserNo"];
    [param setObject:subDict forKey:@"detail"];

enjoy :)

你可能感兴趣的:(iOS中xml的简单构造)