Cocoa - How To Format An XML File
cocoa, nsxml, objective-c
Solution
You can output a nicely formatted XML string using the following:
NSString* string = [xmlNode XMLStringWithOptions:NSXMLNodePrettyPrint];
Note that because `NSXMLDocument` and `NSXMLElement` are subclasses of `NSXMLNode`, you can do this with those classes also.
If you want `NSData` instead of a string, just do:
NSData* xmlData = [xmlNode XMLDataWithOptions:NSXMLNodePrettyPrint];
Problem
Is there a way that I can format an XML file in the proper way when creating it programmatically? For example, if I use this code to create a simple XML File: ``` NSXMLElement *fallback_driver = [[NSXMLElement alloc] initWithName:@"fallback-driver"]; NSXMLElement *folder = [[NSXMLElement alloc] initWithName:@"folder"]; [folder setStringValue:[ads_make objectValueOfSelectedItem]]; NSXMLElement *filename =[[NSXMLElement alloc] initWithName:@"filename"]; [filename setStringValue:ads_driver_name_selected]; [fallback_driver addChild:folder]; [fallback_driver addChild:filename]; NSXMLElement* rootNode = [ads_user_printxml rootElement]; [rootNode addChild:fallback_driver]; ``` When this is run, I would like to output to be as per the commented section in the image below, not the actual XML (that is not commented). How I can format the XML file that way? Thanks! P.S. Thanks for the answer.. However, I would like to convert the NSXMLDocument that I have into NSData for saving... I am trying ``` NSData *newData = [[ads_user_printxml XMLDataWithOptions:NSXMLNodePrettyPrint]XMLData]; ``` however I am getting a warning that "'NSData' may not respond to '-XMLData', where before I added the XMLDataWithOptions it was working fine. I also tried the method 'XMLStringWithOptions' (as you stated - but figured that data was more appropriate), but the same warning was generated. Any ideas? Thanks a lot!