技术的乐趣在于分享,欢迎多多交流,多多沟通。
全部博文(877)
分类: iOS平台
2015-10-19 21:09:46
//创建根节点
GDataXMLElement *rootElement = [GDataXMLNode elementWithName:@"abCASD"];
//创建第一个子节点
GDataXMLElement *element = [GDataXMLNode elementWithName:@"name123" stringValue:@"东方红"];
//设置XML属性
GDataXMLElement *element1 = [GDataXMLNode attributeWithName:@"type" stringValue:@"gif"];
[rootElement addChild:element1];
//添加子节点到根节点上
[rootElement addChild: element];
//使用根节点创建xml文档
GDataXMLDocument *rootDoc = [[GDataXMLDocument alloc] initWithRootElement:rootElement];
//设置使用的xml版本号
[rootDoc setVersion:@"1.0"];
//设置xml文档的字符编码
[rootDoc setCharacterEncoding:@"utf-8"];
//获取并打印xml字符串
NSString *str = [[NSString alloc] initWithData:rootDoc.XMLData encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
//解析XML
GDataXMLElement *root = [rootDoc rootElement];
for (int i=0; i <[rootElement childCount]; i++) {
//GDataXMLElement *element = (GDataXMLElement *)[root childAtIndex:i];
NSLog(@"ROOT Element Name = %@", root.name);
NSLog(@"ROOT Type = %@", [[root attributeForName:@"type"] stringValue]);
GDataXMLElement *element = (GDataXMLElement *)[root childAtIndex:i];
NSLog(@"Element Name = %@", element.name);
NSLog(@"Type = %@", [[element attributeForName:@"type"] stringValue]);
//属性不属于子元素
for (int j=0; j<[element childCount]; j++) {
GDataXMLElement *subItem = (GDataXMLElement *)[element childAtIndex:j];
NSLog(@"Sub Name = %@", subItem.name);
NSLog(@"Sub value = %@", subItem.stringValue);
}
}
//在Xcode中保存XML文件 保存到沙盒中
NSData *data = [rootDoc XMLData];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *contactsPath = [paths objectAtIndex:0];
NSString *filePath = [contactsPath stringByAppendingPathComponent:@"contacts.xml"];
NSLog(@"filePath =========== %@",filePath);
if (![fileManager fileExistsAtPath:filePath]) {
[fileManager createFileAtPath:filePath contents:nil attributes:nil];
}else{
[fileManager removeItemAtPath:filePath error:nil];
}
[data writeToFile:filePath atomically:YES];