您的位置:首页 > 移动开发 > IOS开发

IOS开发之----XML常用操作

2013-02-14 11:54 387 查看


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]]></Sett
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: