Converting NSDictionary to XML

后端 未结 3 1877
滥情空心
滥情空心 2020-12-11 07:52

I need to Post data in XML format. The server accepts a specific xml format. I don\'t want to write the xml by hand, what i want to do is create a NSMutableDictionary<

3条回答
  •  悲哀的现实
    2020-12-11 08:37

    Here is a recursive way to convert a dictionary to a string of XML. It handles dictionaries, arrays, and strings. Dictionary keys are the XML tags and the dictionary objects are used as values or child items in the tree. In the case of an array each element in the array is placed on the same child level with the same tag.

    - (NSString*)ConvertDictionarytoXML:(NSDictionary*)dictionary  withStartElement:(NSString*)startElement{
        NSMutableString *xml = [[NSMutableString alloc] initWithString:@""];
        [xml appendString:@""];
        [xml appendString:[NSString stringWithFormat:@"<%@>",startElement]];
        [self convertNode:dictionary withString:xml andTag:nil];
        [xml appendString:[NSString stringWithFormat:@"",startElement]];
        NSString *finalXML=[xml stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
        NSLog(@"%@",xml);
        return finalXML;
    }
    
    - (void)convertNode:(id)node withString:(NSMutableString *)xml andTag:(NSString *)tag{
        if ([node isKindOfClass:[NSDictionary class]] && !tag) {
        NSArray *keys = [node allKeys];
        for (NSString *key in keys) {
            [self convertNode:[node objectForKey:key] withString:xml andTag:key];
        }
        }else if ([node isKindOfClass:[NSArray class]]) {
            for (id value in node) {
                 [self convertNode:value withString:xml andTag:tag];
            }
        }else {
            [xml appendString:[NSString stringWithFormat:@"<%@>", tag]];
            if ([node isKindOfClass:[NSString class]]) {
            [xml appendString:node];
            }else if ([node isKindOfClass:[NSDictionary class]]) {
                [self convertNode:node withString:xml andTag:nil];
            }
            [xml appendString:[NSString stringWithFormat:@"", tag]];
        }
    }
    

提交回复
热议问题