NSMutable Array to XML file
I have an NSMutableArray of custom objects called Clip. Each clip Object has some NSString properties (clipName,tcIn, tcOut, file path and so on..). How do I write an xml File on disk where each clip in the array is a node of the xml file and its properties are elements of the node?
开发者_StackOverflow中文版Thanks in advance Dario
I think this is what should do you:
//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];
精彩评论