zoukankan      html  css  js  c++  java
  • iOS 解析xml

    1.首先引用委托

    <NSXMLParserDelegate>

    并声明

    NSXMLParser变量。

    2.开始读取xml内容进行解析

    - (IBAction)DoParser:(id)sender {
        
        self.xmlString=@"<?xml version="1.0" encoding="UTF-8"?><root><person id="1"><firstname>尤1</firstname><secondname>吴1</secondname></person><person id="2"><firstname>尤2</firstname><secondname>吴2</secondname></person></root>";
        
        NSData *xmldata=[[NSData alloc]init];
        xmldata=[self.xmlString dataUsingEncoding:NSUTF8StringEncoding];
        
        self.xmlParser=[[NSXMLParser alloc]initWithData:xmldata];
        
        [self.xmlParser setDelegate:self];
        
        
        [self.xmlParser parse];
        
    }
    
    //开始解析 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { NSLog(@"开始处理元素:%@",elementName);
    //可获取元素属性 if ([elementName isEqualToString:@"person"]) { NSLog(@"attributes:%@",[attributeDict objectForKey:@"id"]); } }
    //完成解析 - (void)parserDidEndDocument:(NSXMLParser *)parser{ if (self.soapResults) { self.soapResults=nil; } }
    //元素内的内容 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if (string) { self.soapResults=string; } }
    //结束该元素解析后的操作 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:@"person"]) { //NSLog(@"%@",[NSString stringWithFormat:@"%@",self.soapResults ]); } NSLog(@"%@:%@",elementName,self.soapResults); } //报错时的操作 - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { NSLog(@"%@",parseError); if (self.soapResults) { self.soapResults=nil; } }
  • 相关阅读:
    HDU 1018 Big Number
    UVa 10603 倒水问题
    UVa 12108 特别困的学生
    UVa 1590 IP网络(简单位运算)
    UVa 12325 宝箱
    UVa 253 骰子涂色
    UVa 815 洪水!
    springmvc(2)处理器设配器和映射器
    SpringMVC(1)
    MyBatis(10)逆向工程
  • 原文地址:https://www.cnblogs.com/youyuan1980/p/5019708.html
Copyright © 2011-2022 走看看