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<
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];