xml字串為:
<users>
<user name="hoge" age="20" />
<user name="fuga" age="30" />
</users>
//解析按鈕事件
-(IBAction)btnXml
{
NSString* str= [uitextview1 text];
//string轉成data
NSData *xmlData = [str dataUsingEncoding: NSUTF8StringEncoding];
//對xml進行解析需要使用NSXMLParser類,首先聲明一個NSXMLParser對象
//開始解析
NSXMLParser* xmlRead = [[NSXMLParser alloc] initWithData:xmlData];//初始化NSXMLParser對象
[xmlRead setDelegate:self];//設定NSXMLParser對象的解析方法代理
[xmlRead parse];//調用代理解析NSXMLParser對象,看解析是否成功
}
//解析器,從兩個結點之間讀取內容
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
//NSLog(@"%@",string);}
//獲得結點結尾的值
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
//NSLog(@"%@",elementName);}
//獲得結點頭的值
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
//NSLog(@"%@",elementName);
if([elementName isEqualToString: @"user"])
{
NSString* strName=[attributeDict valueForKey:@"name"];
NSString* strAge=[attributeDict valueForKey:@"age"];
NSString* strUser=uitextview2.text;
strUser=[strUser stringByAppendingFormat:@"姓名:%@,年齡:%@\n",strName,strAge];
[uitextview2 setText:strUser];
//NSLog(@"姓名:%@,年齡:%@", strName,strAge);
}
}
摘自 凡娃軟體