NSMutable Array to XML文件

时间:2011-09-08 21:32:29

标签: objective-c xml

我有一个名为Clip的自定义对象的NSMutableArray。每个剪辑对象都有一些NSString属性(clipName,tcIn,tcOut,文件路径等等)。如何在磁盘上编写xml文件,其中数组中的每个剪辑都是xml文件的节点,其属性是节点的元素?

提前致谢 达里奥

1 个答案:

答案 0 :(得分:3)

我认为这应该是你应该做的:

//Create xml string
NSMutableString *xmlString = [[NSMutableString alloc] init];

//Add all the data to the string
[xmlString appendFormat:@"<clips>"];
for (Clip *c in clipsArray)
{ 
    [xmlString appendFormat:@"\n\t<clip>"];
    [xmlString appendFormat:@"\n\t\t<clipName>%@</clipName>", c.clipName];
    [xmlString appendFormat:@"\n\t\t<tcIn>%@</tcIn>", c.tcIn];
    ...
    [xmlString appendFormat:@"</clip>"];
}
[xmlString appendFormat:@"</clips>"];

//Create a variable to represent the filepath of the outputted file
//This is taken from some code which saves to an iPhone app's documents directory, it might not be ideal
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:@"output.xml"];

//Actually write the information
NSData *data = [xmlString dataUsingEncoding:NSUTF8StringEncoding];
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];