6

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).

xml code

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!

Kevin
  • 1,469
  • 2
  • 19
  • 28

1 Answers1

11

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];
Rob Keniger
  • 45,830
  • 6
  • 101
  • 134
  • Thanks for the answer.. I have modified the original question a little bit.. If you would be so kind as to give me a further hint on how I can actually save to NSData, I would appreciate greatly. I should have mentioned that in the original question. Thanks. – Kevin Apr 25 '12 at 07:58
  • 2
    I've updated my answer. Your edit to your question is correct except that you're calling `XMLData` on the result. That won't work and is unnecessary, because the output of `XMLDataWithOptions:` is an `NSData` object already, not an `NSXMLNode` object. – Rob Keniger Apr 25 '12 at 08:10