首页 > 编程 > JavaScript > 正文

XML文件转化成NSData对象的方法

2019-11-20 11:50:44
字体:
来源:转载
供稿:网友

 

NSData *xmlData = [[NSData alloc]initWithContentsOfFile:[NSString stringWithFormat:@"%@/People.xml",[[NSBundle mainBundle] resourcePath]]];   //2.将xmlData转化成xml文档   GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc]initWithData:xmlData options:0 error:nil];   //3.得到节点   GDataXMLElement *rootElement = xmlDocument.rootElement;   //4.得到子节点 /*NSArray *elementArray = rootElement.children;   //得到classone节点   GDataXMLElement *classoneElement = [elementArray firstObject];   for(GDataXMLElement *element in classoneElement.children)   {     //得到当前节点的文本值     NSLog(@"%@",element.stringValue);     if (element.children.count>0) {       GDataXMLElement *infoElement = [element.children lastObject];       //获得节点的所有属性和属性值       NSArray *attArray = infoElement.attributes;       for (GDataXMLElement *attElement in attArray) {         //得到属性名和属性值         NSLog(@"%@-%@",attElement.name,attElement.stringValue);       }     }   }   */   //模糊查找   NSArray *eArray = [rootElement nodesForXPath:@"//info" error:nil];   NSLog(@"%@",eArray); 

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);  }}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表