Cocoa - 如何格式化XML文件

时间:2022-06-24 16:58:06

Is there a way that I can format an XML file in the proper way when creating it programmatically?

有没有办法在编程时以正确的方式格式化XML文件?

For example, if I use this code to create a simple XML File:

例如,如果我使用此代码创建一个简单的XML文件:

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(没有注释)。

Cocoa  - 如何格式化XML文件

How I can format the XML file that way? Thanks!

我如何以这种方式格式化XML文件?谢谢!

P.S.

附:

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

谢谢你的答案。但是,我想将我拥有的NSXMLDocument转换为NSData以便保存...

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.

但是我收到警告“'NSData'可能没有响应'-XMLData',在我添加XMLDataWithOptions之前它工作得很好。我也尝试了'XMLStringWithOptions'方法(如你所说 - 但是认为数据更多适当的),但产生了相同的警告。

Any ideas? Thanks a lot!

有任何想法吗?非常感谢!

1 个解决方案

#1


11  

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

您可以使用以下命令输出格式良好的XML字符串:

NSString* string = [xmlNode XMLStringWithOptions:NSXMLNodePrettyPrint];

Note that because NSXMLDocument and NSXMLElement are subclasses of NSXMLNode, you can do this with those classes also.

请注意,因为NSXMLDocument和NSXMLElement是NSXMLNode的子类,所以您也可以对这些类执行此操作。

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

如果你想要NSData而不是字符串,只需:

NSData* xmlData = [xmlNode XMLDataWithOptions:NSXMLNodePrettyPrint];

#1


11  

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

您可以使用以下命令输出格式良好的XML字符串:

NSString* string = [xmlNode XMLStringWithOptions:NSXMLNodePrettyPrint];

Note that because NSXMLDocument and NSXMLElement are subclasses of NSXMLNode, you can do this with those classes also.

请注意,因为NSXMLDocument和NSXMLElement是NSXMLNode的子类,所以您也可以对这些类执行此操作。

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

如果你想要NSData而不是字符串,只需:

NSData* xmlData = [xmlNode XMLDataWithOptions:NSXMLNodePrettyPrint];