Convert JSON into XML
If you want to convert the JSON data to XML as we see by iOS there is no by default feature to convert JSON into XML. I have created a method which will convert JSON into XML. The code is written in objective-c, if you want to use that code in swift you have created a class and put a function in that class. After that, you have to insert the .h file into the bridging header (#import “YourClass.h”). then call the method by using:-
1 2 3 4 |
let dict = ["yourJson" : signalName ] as [String : Any] let xmlWriter1 = YourClass() var xmlString = xmlWriter1.convertDictionary(toXML: dict, withStartElement: "HeaderName", isFirstElement: true) print(xmlString!) |
Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
- (NSString*)convertDictionaryToXML:(NSDictionary*)dictionary withStartElement:(NSString*)startElement isFirstElement:(BOOL) isFirstElement { NSMutableString *xml = [[NSMutableString alloc] initWithString:@""]; NSArray *arr = [dictionary allKeys]; if (isFirstElement) { [xml appendString:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\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; } |