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]){ -
return NO; -
} -
} -
-
NSData *xmlData = [xmlDoucment XMLDataWithOptions:NSXMLNodePrettyPrint]; -
if (![xmlData writeToFile:destPath atomically:YES]) { -
NSLog(@"Could not write document out..."); -
return NO; -
} -
-
return YES; - }
4. 生成CData节点
- -
(NSXMLNode *)generateCDataNode:(NSString *)value { - <span
style="white-space:pre"> </span>NSXMLNode *cdataNode = [[NSXMLNode alloc] initWithKind:NSXMLTextKind options:NSXMLNodeIsCDATA]; - <span
style="white-space:pre"> </span>[cdataNode setStringValue:value]; - <span
style="white-space:pre"> </span> - <span
style="white-space:pre"> </span>return [cdataNode autorelease]; - }
可以像下面这样使用:
- NSXMLElement
*urlNode = [NSXMLElement elementWithName:@"Setting"]; -
NSXMLNode *cdataNode = [self generateCDataNode:dmgFileName]; -
[urlNode addAttribute:[NSXMLNode attributeWithName:@"name" stringValue:name]]; -
[urlNode addAttribute:[NSXMLNode attributeWithName:@"type" stringValue:type]]; -
[urlNode addChild:cdataNode];
生成的Xml节点如下:
- <Setting
name="OutputFileName" type="string"><![CDATA[mac-data-recovery_full737.dmg]]></Setting>