iPhone开发 解析xml NSData
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);
}
}
摘自 凡娃软件
相关新闻>>
- 发表评论
-
- 最新评论 更多>>