XML文档节点如下:
<Party>
<Player>
<Name>Butch</Name>
<Level>1</Level>
<Class>Fighter</Class>
</Player>
<Player>
<Name>Shadow</Name>
<Level>2</Level>
<Class>Rogue</Class>
</Player>
</Party>
//第一种需要各属性名
NSString *path = [[NSBundle mainBundle] pathForResource:@"hh.xml" ofType:nil];
NSData * data = [NSData dataWithContentsOfFile:path];
DDXMLDocument *doc = [[DDXMLDocument alloc] initWithData:data options:0 error:nil];
NSArray *items = [doc nodesForXPath:@"//Party/Player" error:nil];
for (DDXMLElement *item in items) {
NSArray *names = [item elementsForName:@"Name"];
for(DDXMLElement *name in names) {
NSLog(@"姓名 %@",name.stringValue) ;
break;
}
NSArray *levels = [item elementsForName:@"Level"];
for(DDXMLElement *level in levels) {
NSLog(@"等级 %@",level.stringValue) ;
break;
}
NSArray *classes = [item elementsForName:@"Class"];
for(DDXMLElement *class in classes) {
NSLog(@"类别 %@",class.stringValue) ;
break;
}
}
//第二种只需要走訪的節點
NSString *path = [[NSBundle mainBundle] pathForResource:@"hh.xml" ofType:nil];
//將XML檔案讀出
NSString *xmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//開始使用KissXML,將讀出的XML字串指定給DDXMLDocument物件
DDXMLDocument *xmlDoc = [[DDXMLDocument alloc]initWithXMLString:xmlString options:0 error:nil];
//釋放
xmlString = nil;
//開始解析
NSArray *children = nil;
//使用XPath取得要走訪的節點
children = [xmlDoc nodesForXPath:@"Party/Player" error:nil];
//依符合的節點數量走訪
for (int i=0; i < [children count]; i++) {
//建立DDXMLNode
DDXMLNode *child = [children objectAtIndex:i];
NSLog(@"1:%@", [[child childAtIndex:0] stringValue]);
NSLog(@"2:%@", [[child childAtIndex:1] stringValue]);
NSLog(@"3:%@", [[child childAtIndex:2] stringValue]);
}
//第一种字符串
NSString *str = @"<body xmlns:food='http://example.com/' food:genre='italian'>"
@" <food:pizza>yumyum</food:pizza>"
@"</body>";
//得到目录
DDXMLDocument * doc1 = [[DDXMLDocument alloc] initWithXMLString:str options:0 error:nil];
NSArray *items1 = [doc1 nodesForXPath:@"//body" error:nil];
for (DDXMLElement *item in items1) {
NSArray *names = [item elementsForName:@"food:pizza"];
for(DDXMLElement *name in names) {
NSLog(@"节点: %@",name.stringValue) ;
break;
}
}
//第二种字符串解析
NSString *str = @"<body xmlns:food='http://example.com/' food:genre='italian'>"
@" <food:pizza>yumyum</food:pizza>"
@"</body>";
//將XML檔案讀出
NSString *xmlString = str;
//開始使用KissXML,將讀出的XML字串指定給DDXMLDocument物件
DDXMLDocument *xmlDoc = [[DDXMLDocument alloc]initWithXMLString:xmlString options:0 error:nil];
//釋放
xmlString = nil;
//開始解析
NSArray *children = nil;
//使用XPath取得要走訪的節點
children = [xmlDoc nodesForXPath:@"body" error:nil];
NSLog(@"%@",children);
//依符合的節點數量走訪
for (int i=0; i < [children count]; i++) {
//建立DDXMLNode
DDXMLNode *child = [children objectAtIndex:i];
NSLog(@"1:%@", [[child childAtIndex:0] stringValue]);
}