Cocoa - How to format an XML file

Is there a way that I can correctly format an XML file when programmatically programming it?

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 done, I would like to output it according to the comments section in the image below, and not with the actual XML (which is not commented out).

xml code

How can I format the xml file this way? Thanks!

PS

Thanks for the answer. However, I would like to convert the NSXMLDocument that I have to NSData to save ...

I'm trying to

 NSData *newData = [[ads_user_printxml XMLDataWithOptions:NSXMLNodePrettyPrint]XMLData]; 

however, I get a warning that "NSData" may not respond to "-XMLData", where before I added XMLDataWithOptions, it worked fine. I also tried the XMLStringWithOptions method (as you said), but realized that the data was more appropriate), but the same warning was received.

Any ideas? Many thanks!

+6
source share
1 answer

You can output a beautifully formatted XML string using the following:

 NSString* string = [xmlNode XMLStringWithOptions:NSXMLNodePrettyPrint]; 

Note that since NSXMLDocument and NSXMLElement are subclasses of NSXMLNode , you can do this with these classes as well.

If you want NSData instead of a string, just do:

 NSData* xmlData = [xmlNode XMLDataWithOptions:NSXMLNodePrettyPrint]; 
+11
source

Source: https://habr.com/ru/post/914092/


All Articles