创建XML文件
- //创建XML文件
- -(NSXMLDocument*)createXMLDocument:(NSString*)rootName{
- NSLog(@"%@withrootName%@",NSStringFromSelector(_cmd),rootName);
- NSXMLElement*root=(NSXMLElement*)[NSXMLNodeelementWithName:rootName];
- [rootaddAttribute:[NSXMLNodeattributeWithName:@"version"stringValue:@"1.0"]];
- NSXMLDocument*xmlDoc=[[NSXMLDocumentalloc]initWithRootElement:root];
- [xmlDocsetVersion:@"1.0"];
- [xmlDocsetCharacterEncoding:@"UTF-8"];
- [xmlDocsetRootElement:root];
- return[xmlDocautorelease];
- }
2. 装载XML文件
- -(NSXMLDocument*)loadXMLDocument:(NSString*)xmlFilePath{
- assert(xmlFilePath);
- NSXMLDocument*xmlDoc=nil;
- NSError*error=nil;
- @try{
- NSURL*fileURL=[NSURLfileURLWithPath:xmlFilePath];
- if(fileURL==nil){
- returnnil;
- }
- xmlDoc=[[NSXMLDocumentalloc]initWithContentsOfURL:fileURLoptions:NSXMLDocumentTidyXMLerror:&error];
- @catch(NSException*e){
- }
- @finally{
- return[xmlDocautorelease];
- }
3. 保存XML文件
- -(BOOL)saveXMLFile:(NSString*)destPath:(NSXMLDocument*)xmlDoucment{
- if(xmlDoucment==nil){
- returnNO;
- }
- if(![[NSFileManagerdefaultManager]fileExistsAtPath:destPath]){
- if(![[NSFileManagerdefaultManager]createFileAtPath:destPathcontents:nilattributes:nil]){
- returnNO;
- }
- NSData*xmlData=[xmlDoucmentXMLDataWithOptions:NSXMLNodePrettyPrint];
- if(![xmlDatawriteToFile:destPathatomically:YES]){
- NSLog(@"Couldnotwritedocumentout...");
- returnYES;
- }
4. 生成CData节点
- -(NSXMLNode*)generateCDatanode:(NSString*)value{
- <spanstyle="white-space:pre"></span>NSXMLNode*cdatanode=[[NSXMLNodealloc]initWithKind:NSXMLTextKindoptions:NSXMLNodeIsCDATA];
- <spanstyle="white-space:pre"></span>[cdatanodesetStringValue:value];
- <spanstyle="white-space:pre"></span>
- <spanstyle="white-space:pre"></span>return[cdatanodeautorelease];
- }
可以像下面这样使用:
- NSXMLElement*urlNode=[NSXMLElementelementWithName:@"Setting"];
- NSXMLNode*cdatanode=[selfgenerateCDatanode:dmgFileName];
- [urlNodeaddAttribute:[NSXMLNodeattributeWithName:@"name"stringValue:name]];
- [urlNodeaddAttribute:[NSXMLNodeattributeWithName:@"type"stringValue:type]];
- [urlNodeaddChild:cdatanode];