- (void)getData
{
//一个字典
self.dic = [[NSMutableDictionary alloc] initWithCapacity:10];
// 获取包里面city.xml路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"xml"];
//二进制数据
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
//GDataXMLDocument开始解析xml
GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil]
//获得根节点
GDataXMLElement *root = document.rootElement;
//根节点下的所有子节点(不包括孙子节点等)
NSArray *rootson = [root children];
// 遍历根节点的子节点
for (GDataXMLElement * element in rootson) {
//所有的city按以省名为key放入字典中
NSMutableArray *ary = [self.dic objectForKey:element.name];
if (ary == nil) {
ary = [[NSMutableArray alloc] initWithCapacity:20];
[self.dic setObject:ary forKey:element.name];
}
NSArray *citys = element.children;
for (GDataXMLElement *city in citys) {
//[self.dic setObject:city.stringValue forKey:city.name];
[ary addObject:city.stringValue];
}
}
}
2.第二种遍历方法
- (void)getData1
{
self.dic = [[NSMutableDictionary alloc] initWithCapacity:10];
NSString *path = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"xml"];
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil];
GDataXMLElement *root = document.rootElement;
//下面解析开始 此种方法采用 nodesForXpath
NSArray *prov = @[@"河南",@"河北"];
for(int i=0 ;i<[prov count];i++)
{
//通过 nodesForXPath 可以获得root节点(此处root为根节点,也可以不是根节点)下得所有 符合//%@/city 格式的节点,
//%@是 河南,河北等, 通过此格式,获得所有的city节点(可以是孙子节点),限制是此city节点的父节点必须是 %@
NSArray *array = [root nodesForXPath:[NSString stringWithFormat:@"//%@/city",prov[i]] error:nil];
//获得所有的 河南(或河北)下的city后,以河南(河北)为key放入字典
for (GDataXMLElement *element in array) {
NSMutableArray *ary = [self.dic objectForKey:prov[i]];
if (ary == nil) {
ary = [[NSMutableArray alloc] initWithCapacity:20];
[self.dic setObject:ary forKey:prov[i]];
}
[ary addObject:element.stringValue];
}
}
}
注:
elementsForName这个方法也可以通过名字获得节点 ,和nodesForXPath类似,但仅限于获得子节点