xml读写--谁知道这几个方法怎么用都需要什么框架(请留言)

前端之家收集整理的这篇文章主要介绍了xml读写--谁知道这几个方法怎么用都需要什么框架(请留言)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
创建XML文件

  1. //创建XML文件
  2. -(NSXMLDocument*)createXMLDocument:(NSString*)rootName{
  3. NSLog(@"%@withrootName%@",NSStringFromSelector(_cmd),rootName);
  4. NSXMLElement*root=(NSXMLElement*)[NSXMLNodeelementWithName:rootName];
  5. [rootaddAttribute:[NSXMLNodeattributeWithName:@"version"stringValue:@"1.0"]];
  6. NSXMLDocument*xmlDoc=[[NSXMLDocumentalloc]initWithRootElement:root];
  7. [xmlDocsetVersion:@"1.0"];
  8. [xmlDocsetCharacterEncoding:@"UTF-8"];
  9. [xmlDocsetRootElement:root];
  10. return[xmlDocautorelease];
  11. }

2. 装载XML文件


    -(NSXMLDocument*)loadXMLDocument:(NSString*)xmlFilePath{
  1. assert(xmlFilePath);
  2. NSXMLDocument*xmlDoc=nil;
  3. NSError*error=nil;
  4. @try{
  5. NSURL*fileURL=[NSURLfileURLWithPath:xmlFilePath];
  6. if(fileURL==nil){
  7. returnnil;
  8. }
  9. xmlDoc=[[NSXMLDocumentalloc]initWithContentsOfURL:fileURLoptions:NSXMLDocumentTidyXMLerror:&error];
  10. @catch(NSException*e){
  11. }
  12. @finally{
  13. return[xmlDocautorelease];
  14. }

3. 保存XML文件


  1. -(BOOL)saveXMLFile:(NSString*)destPath:(NSXMLDocument*)xmlDoucment{
  2. if(xmlDoucment==nil){
  3. returnNO;
  4. }
  5. if(![[NSFileManagerdefaultManager]fileExistsAtPath:destPath]){
  6. if(![[NSFileManagerdefaultManager]createFileAtPath:destPathcontents:nilattributes:nil]){
  7. returnNO;
  8. }
  9. NSData*xmlData=[xmlDoucmentXMLDataWithOptions:NSXMLNodePrettyPrint];
  10. if(![xmlDatawriteToFile:destPathatomically:YES]){
  11. NSLog(@"Couldnotwritedocumentout...");
  12. returnYES;
  13. }

4. 生成CData节点


    -(NSXMLNode*)generateCDatanode:(NSString*)value{
  1. <spanstyle="white-space:pre"></span>NSXMLNode*cdatanode=[[NSXMLNodealloc]initWithKind:NSXMLTextKindoptions:NSXMLNodeIsCDATA];
  2. <spanstyle="white-space:pre"></span>[cdatanodesetStringValue:value];
  3. <spanstyle="white-space:pre"></span>
  4. <spanstyle="white-space:pre"></span>return[cdatanodeautorelease];
  5. }

可以像下面这样使用:

    NSXMLElement*urlNode=[NSXMLElementelementWithName:@"Setting"];
  1. NSXMLNode*cdatanode=[selfgenerateCDatanode:dmgFileName];
  2. [urlNodeaddAttribute:[NSXMLNodeattributeWithName:@"name"stringValue:name]];
  3. [urlNodeaddAttribute:[NSXMLNodeattributeWithName:@"type"stringValue:type]];
  4. [urlNodeaddChild:cdatanode];

生成的Xml节点如下:


    <@H_541_301@Setting@H_541_301@name="OutputFileName"type="string">@H_541_301@<![CDATA[mac-data-recovery_full737.dmg]]></@H_541_301@Setting@H_541_301@>@H_541_301@

猜你在找的XML相关文章