XML常用操作

来源:互联网 发布:网络推广专员的kpi 编辑:程序博客网 时间:2024/05/20 03:07

1.创建XML文件


  1. //创建XML文件  
  2. (NSXMLDocument *)createXMLDocument:(NSString *)rootName{  
  3.     NSLog(@"%@ with rootName %@", NSStringFromSelector(_cmd), rootName);  
  4.     NSXMLElement *root (NSXMLElement *)[NSXMLNode elementWithName:rootName];  
  5.     [root addAttribute:[NSXMLNode attributeWithName:@"version" stringValue:@"1.0"]];  
  6.     NSXMLDocument *xmlDoc [[NSXMLDocument alloc] initWithRootElement:root];  
  7.     [xmlDoc setVersion:@"1.0"];  
  8.     [xmlDoc setCharacterEncoding:@"UTF-8"];  
  9.     [xmlDoc setRootElement:root];  
  10.       
  11.     return [xmlDoc autorelease];  
  12.  

2. 装载XML文件


  1. (NSXMLDocument *)loadXMLDocument:(NSString *)xmlFilePath{  
  2.     assert(xmlFilePath);  
  3.     NSXMLDocument *xmlDoc nil;  
  4.     NSError *error nil;  
  5.     @try  
  6.         NSURL *fileURL [NSURL fileURLWithPath:xmlFilePath];  
  7.         if (fileURL == nil)  
  8.             return nil;  
  9.          
  10.         xmlDoc [[NSXMLDocument alloc] initWithContentsOfURL:fileURL options:NSXMLDocumentTidyXML error:&error];  
  11.      
  12.     @catch (NSException e)  
  13.           
  14.      
  15.     @finally  
  16.         return [xmlDoc autorelease];  
  17.      
  18.  

3. 保存XML文件


  1. (BOOL) saveXMLFile:(NSString *)destPath :(NSXMLDocument *)xmlDoucment{  
  2.     if (xmlDoucment == nil)  
  3.         return NO;  
  4.      
  5.       
  6.     if [[NSFileManager defaultManager] fileExistsAtPath:destPath])  
  7.         if [[NSFileManager defaultManager] createFileAtPath:destPath contents:nil attributes:nil]){  
  8.             return NO;  
  9.          
  10.      
  11.   
  12.     NSData *xmlData [xmlDoucment XMLDataWithOptions:NSXMLNodePrettyPrint];   
  13.     if (![xmlData writeToFile:destPath atomically:YES])  
  14.         NSLog(@"Could not write document out...");  
  15.         return NO;  
  16.      
  17.       
  18.     return YES;  
  19.  

4. 生成CData节点


  1. (NSXMLNode *)generateCDataNode:(NSString *)value  
  2. <span style="white-space:pre">  </span>NSXMLNode *cdataNode [[NSXMLNode alloc] initWithKind:NSXMLTextKind options:NSXMLNodeIsCDATA];  
  3. <span style="white-space:pre">  </span>[cdataNode setStringValue:value];  
  4. <span style="white-space:pre">  </span>  
  5. <span style="white-space:pre">  </span>return [cdataNode autorelease];  
  6.  

可以像下面这样使用:

  1. NSXMLElement *urlNode [NSXMLElement elementWithName:@"Setting"];  
  2.     NSXMLNode *cdataNode [self generateCDataNode:dmgFileName];  
  3.     [urlNode addAttribute:[NSXMLNode attributeWithName:@"name" stringValue:name]];  
  4.     [urlNode addAttribute:[NSXMLNode attributeWithName:@"type" stringValue:type]];  
  5.     [urlNode addChild:cdataNode];  

生成的Xml节点如下:

 


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