0

我正在使用 XMWriter 类生成 XML,但是在生成我的 XML 字符串后,我不确定如何将其保存为 XML 文件。

.m 代码

[xmlWriter writeEndElement];
[xmlWriter writeStartElement:@"Miniparent"];
[xmlWriter writeStartElement:@"Child"];
[xmlWriter writeCharacters:@"Text content for root element"];
[xmlWriter writeEndElement];
[xmlWriter writeStartElement:@"Child"];
[xmlWriter writeCharacters:@"Text content for root element"];
[xmlWriter writeEndElement];

控制台输出

<Miniparent>
<Child>Text content for root element</Child>
<Child>Text content for root element</Child>
<Child>Text content for root element</Child>
</Miniparent>
4

2 回答 2

1

将其转换为 NSString 对象

NSString* xml = [xmlWriter toString];

然后将其保存到文件

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory

NSError *error = nil;
BOOL succeed = [xml writeToFile:[documentsDirectory stringByAppendingPathComponent:@"myXmlFile.xml"]
      atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
    // Handle error here
}
于 2013-04-03T11:19:16.643 回答
1

我解决了我的问题如下,并将此代码提供给其他用户

NSFileManager *fileManager = [NSFileManager defaultManager];

//getting the path to document directory for the file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [paths objectAtIndex:0];
NSString *path = [documentDir stringByAppendingPathComponent:@"test.xml"];

//checking to see of the file already exist
if(![fileManager fileExistsAtPath:path])
{
    [fileManager createFileAtPath:path contents:[xml dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
}
于 2013-04-03T11:30:20.843 回答