微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

GDataXMLNode解析xml文件

转载请标明出处

欢迎交流

zltqzj@163.com

我是一个单线程妞~





Nsstring* path = [[NSBundle mainBundle] pathForResource:@"StudentXML" ofType:@"xml"];
    NSData* data = [[NSData alloc] initWithContentsOfFile:path];
    GdataxMLDocument* doc = [[GdataxMLDocument alloc] initWithData:data options:0 error:nil];
    GdataxMLElement* root = [doc rootElement];//所有内容
    
    // 取标签中的内容方法:1,路径。2,childAtIndex
    //(1)路径
    NSArray* fistName = [root nodesForXPath:@"//student/name/fistName" error:nil];// 所t有标签为fistName的元素。
    NSLog(@"1:%@",[[fistName objectAtIndex:1] stringValue]);
    // (2)childAtIndex
    GdataxMLNode* lastName = [[[root childAtIndex:1] childAtIndex:0] childAtIndex:1];
    NSLog(@"2:%@",[lastName stringValue]);

代码下载地址:http://download.csdn.net/detail/sijiazhentan/6270435


解析稍微复杂的页面:http://api.hudong.com/iphonexml.do?type=focus-c

代码如下:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize recieveData = _recieveData;

- (id)initWithNibName:(Nsstring *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSURL* url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];
    
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    
    // Do any additional setup after loading the view from its nib.
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    _recieveData = [[NSMutableData alloc] init];
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.recieveData  appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    Nsstring* str = [[Nsstring alloc] initWithData:self.recieveData encoding:NSUTF8StringEncoding];
    
    _recieveData = nil;
    

    GdataxMLDocument* doc = [[GdataxMLDocument alloc] initWithXMLString:str options:0 error:nil];
    GdataxMLElement* root = [doc rootElement];
    
 
    NSArray* array =[root nodesForXPath:@"//response/docList/docInfo" error:nil];
    for (int i =0; i<array.count; i++) {
         NSLog(@"每项内容的题目:%@",[[[[array objectAtIndex:i] elementsForName:@"docTitle"] objectAtIndex:0] stringValue] );
    }
    
    
   
    
    
    _recieveData = nil;
    
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // dispose of any resources that can be recreated.
}

@end

原文地址:https://www.jb51.cc/xml/299842.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。