Converting NSDictionary to XML

后端 未结 3 1878
滥情空心
滥情空心 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:34

    If you wouldn't use libraries or need additional customization:

    - (NSString*)convertDictionaryToXML:(NSDictionary*)dictionary withStartElement:(NSString*)startElement
    {
        return [self convertDictionaryToXML:dictionary withStartElement:startElement isFirstElement:YES];
    }
    
    - (NSString*)convertDictionaryToXML:(NSDictionary*)dictionary withStartElement:(NSString*)startElement isFirstElement:(BOOL) isFirstElement
    {
        NSMutableString *xml = [[NSMutableString alloc] initWithString:@""];
        NSArray *arr = [dictionary allKeys];
        if (isFirstElement)
        {
            [xml appendString:@"\n"];
        }
        [xml appendString:[NSString stringWithFormat:@"<%@>\n", startElement]];
        for(int i=0; i < [arr count]; i++)
        {
            NSString *nodeName = [arr objectAtIndex:i];
            id nodeValue = [dictionary objectForKey:nodeName];
            if([nodeValue isKindOfClass:[NSArray class]])
            {
                if([nodeValue count]>0)
                {
                    for(int j=0;j<[nodeValue count];j++)
                    {
                        id value = [nodeValue objectAtIndex:j];
                        if([value isKindOfClass:[NSDictionary class]])
                        {
                            [xml appendString:[self convertDictionaryToXML:value withStartElement:nodeName isFirstElement:NO]];
                        }
                    }
                }
            }
            else if([nodeValue isKindOfClass:[NSDictionary class]])
            {
                [xml appendString:[self convertDictionaryToXML:nodeValue withStartElement:nodeName isFirstElement:NO]];
            }
            else
            {
                if([nodeValue length]>0){
                    [xml appendString:[NSString stringWithFormat:@"<%@>",nodeName]];
                    [xml appendString:[NSString stringWithFormat:@"%@",[dictionary objectForKey:nodeName]]];
                    [xml appendString:[NSString stringWithFormat:@"\n",nodeName]];
                }
            }
        }
    
        [xml appendString:[NSString stringWithFormat:@"\n",startElement]];
    
        NSString *finalxml=[xml stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
    
        return finalxml;
    }
    

    and call this as:

    NSString *xmlString = [self convertDictionaryToXML:data withStartElement:startElementName];
    

提交回复
热议问题