how to create xml file in objective c cocoa

4k Views Asked by At

I m new to xcode and objective c cocoa framework and i want to write xml data to xml file placed in my cocoa project's resources folder but i cant write data to file. Anybody help please.

NSXMLElement *root = [[NSXMLElement alloc] initWithName:@"Request"];
[root addAttribute:[NSXMLNode attributeWithName:@"Attribute1" stringValue:@"Value1"]];
[root addAttribute:[NSXMLNode attributeWithName:@"Attribute2" stringValue:@"Value2"]];
[root addAttribute:[NSXMLNode attributeWithName:@"Attribute3" stringValue:@"Value3"]];

NSXMLElement *childElement1 = [[NSXMLElement alloc] initWithName:@"ChildElement1"];
[root addChild:childElement1];
[childElement1 release];

NSXMLElement *childElement2 = [[NSXMLElement alloc] initWithName:@"ChildElement2"];
[childElement2 addAttribute:[NSXMLNode attributeWithName:@"ChildAttribute2.1" stringValue:@"Value2.1"]];
[childElement2 setStringValue:@"ChildValue2.1"];
[root addChild:childElement2];
[childElement2 release];

NSXMLDocument *xmlRequest = [NSXMLDocument documentWithRootElement:root];
[root release];
NSLog(@"XML Document\n%@", xmlRequest);//till this art code runs fine.
but when next part starts i got bad exception and code stops.
NSData *xmlData = [xmlRequest XMLDataWithOptions:NSXMLNodePrettyPrint];
[xmlData writeToFile:@"/Users/halen/Documents/project3/xmlsample.xml" atomically:YES];
[xmlRequest release];

I dont know whats the problem is there is any problem with the xml file placement. where to place xml file?? And what is right way to write xml data to .xml file?

2

There are 2 best solutions below

2
On

writeToFile: expects a path. You haven't supplied a valid path.

5
On

Try this method

[[NSFileManager defaultManager] createFileAtPath:@"/Some/Path/foo.xml"
                            contents:xmlData
                            attributes:nil];