objective-c 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]){
			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 {
	NSXMLNode *cdataNode = [[NSXMLNode alloc] initWithKind:NSXMLTextKind options:NSXMLNodeIsCDATA];
	[cdataNode setStringValue:value];
	
	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>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章