简体   繁体   English

如何在目标C可可中创建xml文件

[英]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. 我是Xcode和Objective C可可框架的新手,我想将xml数据写入放置在可可项目资源文件夹中的xml文件中,但无法将数据写入文件中。 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. 我不知道这是什么问题,xml文件放置有任何问题。 where to place xml file?? 在哪里放置xml文件? And what is right way to write xml data to .xml file? 将XML数据写入.xml文件的正确方法是什么?

writeToFile: expects a path. writeToFile:需要一个路径。 You haven't supplied a valid path. 您尚未提供有效路径。

Try this method 试试这个方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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