iOS開發之XML解析代碼,iosxml解析
iOS開發之XML解析代碼
//1.載入和解析XML檔案 NSString *path = [[NSBundle mainBundle] pathForResource:@"xml.txt" ofType:nil]; NSData *data = [[NSData alloc] initWithContentsOfFile:path]; // GDataXMLDocument 表示XML文檔對象 // initWithData 使用NSData初始化, 就是解析 GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil]; //2.擷取指定結點 XPath //CityName路徑: /root/systemConfig/CityName NSArray *array = [doc nodesForXPath:@"/root/systemConfig/CityName" error:nil]; //CityName GDataXMLElement *element = [array firstObject]; NSLog(@"name=%@ value=%@",element.name,element.stringValue); //3.擷取指定結點的屬性 NSArray *items = [doc nodesForXPath:@"/root/systemConfig/ComeChannel/Item" error:nil]; GDataXMLElement *item = [items firstObject]; //擷取屬性, 屬性使用GDataXMLElement表示 for(GDataXMLElement *attr in item.attributes) { NSLog(@"a-name=%@ avalue=%@",attr.name,attr.stringValue); } //4.擷取所有指定名字的結點(不管位置) //XPath文法: //Item NSArray *allItem = [doc nodesForXPath:@"//Item" error:nil]; for (GDataXMLElement *e in allItem) { NSLog(@"name = %@",e.name); } //5.擷取所有指定名字的屬性(不管哪個結點的) //XPath文法: //@value NSArray *allValue = [doc nodesForXPath:@"//@value" error:nil]; for (GDataXMLElement *e in allValue) { NSLog(@"value = %@",e.stringValue); } //6.逐層遍曆XML檔案 //擷取根節點 GDataXMLElement *root = doc.rootElement; //擷取子節點 //root.children //擷取子節點個數 //root.childCount //擷取指定名字的子節點 //root elementsForName:<#(NSString *)#>}
: