简体   繁体   中英

how to create xml file in objective c cocoa

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?

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

Try this method

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM