我正在使用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>
答案 0 :(得分: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
}
答案 1 :(得分: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];
}