网络解析之XML及JSON

首先要加入类库GDataXMLNode和JSON

解析本地文件Students.txt

<students>

    <student>

        <name>汤姆 </name>

        <age>20</age> 

        <phone>13049640144</phone>

     </student> 

     <student>

        <name> 吉米</name>

        <age>20</age> 

        <phone>13049640144</phone>

     </student> 

     <student>

        <name> 螺丝</name>

        <age>20</age> 

        <phone>13049640144</phone>

     </student>       

</students>

    //XML解析 

 

    NSString *str = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"Students"               ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil];

 

    //解析XML,把结果放在document里面

    GDataXMLDocument *document = [[GDataXMLDocument alloc]initWithXMLString:str options:0 error:nil];

    GDataXMLElement *root = [document rootElement];//获得根结点

 

    NSArray *arr = [root nodesForXPath:@"//name" error:nil];

    //遍历节点

    for(GDataXMLElement *name in arr)

    {

        NSLog(@"%@",[name stringValue]);

    }


    //Json解析

    NSString *str = @"[{\"name\":\"kelly\",\"age\":\"23\",\"sex\":\"女\"},{\"name\":\"evnxy\",\"age\":\"21\",\"sex\":\"女\"}]";

   NSArray *arr = [str JSONValue];

    NSLog(@"%@",arr);

posted @ 2016-06-19 22:37  白白的iOS之行  阅读(208)  评论(0)    收藏  举报