使用KissXML前的操作
1. 使用KissXML必须导入libxml2.2.dylib框架
2. 在Header Research Paths中添加路径:/usr/include/libxml2
创建
//创建根元素结点
GDataXMLElement *rootElement = [GDataXMLElement elementWithName:@"China"];
NSArray *provinces = @[@"Henan", @"Zhejiang", @"Jiangsu"];
NSArray *citys = @[@[@"郑州", @"洛阳"],
@[@"杭州", @"金华", @"台州"],
@[@"南京", @"苏州", @"无锡"]];
for (int i = 0; i < 3; i++) {
//创建第二层元素结点
GDataXMLElement *province = [GDataXMLElement elementWithName:@"province"];
//创建第二层元素结点的属性结点
GDataXMLElement *provinceName = [GDataXMLElement elementWithName:@"name" stringValue:provinces[i]];
//第二层元素结点添加属性结点
[province addAttribute:provinceName];
for (NSString *string in citys[i]) {
//创建第三层元素结点
GDataXMLElement *city = [GDataXMLElement elementWithName:@"city" stringValue:string];
//第二层元素结点添加子节点(第三层元素结点)
[province addChild:city];
}
//根元素结点添加子节点(第二层元素结点)
[rootElement addChild:province];
}
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithRootElement:rootElement];
[doc setVersion:@"2.0"];
[doc setCharacterEncoding:@"UTF-8"];
NSData *data = doc.XMLData;
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/city.xml"];
NSLog(@"%@", filePath);
[data writeToFile:filePath atomically:YES];
读取
forin遍历
- (IBAction)readXML:(id)sender {
//读取文件
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"xml" ofType:@"xml"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
//解析成文档
GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:data error:nil];
//获取根元素结点
GDataXMLElement *rootElement = document.rootElement;
//获取根元素结点的属性结点
GDataXMLNode *rootNode = [rootElement attributeForName:@"name"];
//打印根元素结点的属性结点的名字和字符串值
NSLog(@"%@", rootNode.stringValue);
//在根元素结点的子节点数组中遍历第二层元素结点
for (GDataXMLElement *element in rootElement.children) {
//获取第二层元素结点的属性结点
GDataXMLNode *node1 = [element attributeForName:@"name"];
NSLog(@"%@", node1.stringValue);
//在第二层元素结点的子节点数组中遍历第三层元素结点
for (GDataXMLElement *sonElement in element.children) {
//在第三层元素结点的子节点数组中遍历第四层元素结点
for (GDataXMLNode *grandsonElement in sonElement.children) {
//打印第四层元素结点的名字和字符串值
NSLog(@"%@:%@", grandsonElement.name, grandsonElement.stringValue);
}
}
}
}
XPath遍历
//遍历与属性有关的结点
/*
//@country //所有是country的属性结点
//cd[@country] //所有含有country属性的cd元素结点
//cd[@*] //所有含有属性的元素结点
//cd[@country=\"USA\"] //所有含有country="USA"属性的cd元素结点
*/
- (IBAction)xpathReadXML:(UIButton *)sender {
//读取XML文件
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"xml2" ofType:@"xml"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
//解析XML文档
GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:data error:nil];
//创建XPath路径
NSString *XPath = @"//cd[@*]";
//查找符合XPath路径的所有结点
NSArray *array = [document nodesForXPath:XPath error:nil];
//遍历所有结点
for (GDataXMLElement *element in array) {
//打印结点的名字和字符串值
NSLog(@"name:%@\nstringValue:%@", element.name, element.stringValue);
}
}