background image

IOS 开发之—-XML 常用操作

1.创建 XML 文件
//创建 XML 文件  
- (NSXMLDocument *)createXMLDocument:(NSString *)rootName{  
    NSLog(@”%@ with rootName %@”, NSStringFromSelector(_cmd), rootName);  
    NSXMLElement *root = (NSXMLElement *)[NSXMLNode elementWithName:rootName];  
    [root addAttribute:[NSXMLNode attributeWithName:@"version" stringValue:@"1.0"]];  
    NSXMLDocument *xmlDoc = [[NSXMLDocument alloc] initWithRootElement:root];  
    [xmlDoc setVersion:@"1.0"];  
    [xmlDoc setCharacterEncoding:@"UTF-8"];  
    [xmlDoc setRootElement:root];  
      
    return [xmlDoc autorelease];  
}  

2. 装载 XML 文件
- (NSXMLDocument *)loadXMLDocument:(NSString *)xmlFilePath{  
    assert(xmlFilePath);  
    NSXMLDocument *xmlDoc = nil;  
    NSError *error = nil;  
    @try {  
        NSURL *fileURL = [NSURL fileURLWithPath:xmlFilePath];  
        if (fileURL == nil) {  
            return nil;  
        }  
               xmlDoc  =  [[NSXMLDocument  alloc]  initWithContentsOfURL:fileURL 
options:NSXMLDocumentTidyXML error:&error];  
    }  
    @catch (NSException * e) {  
          
    }  
    @finally {  
        return [xmlDoc autorelease];  
    }  
}  
3. 保存 XML 文件
-  (BOOL)  saveXMLFile:(NSString  *)destPath  NSXMLDocument *)xmlDoucment{  
    if (xmlDoucment == nil) {  
        return NO;  
    }  
      
    if ( ! [[NSFileManager defaultManager] fileExistsAtPath:destPath]) {  
        if ( ! [[NSFileManager defaultManager] createFileAtPath:destPath contents:nil attributes:nil])