IOS 网络解析(XML,JSON)

首先要加入类库GDataXMLNode和JSON

解析本地文件Students.txt

 <students>
    <student>
        <name> 小朋 </name>
        <age>20</age> 
        <phone>1324525255</phone>
     </student> 
     <student>
        <name> 小天 </name>
        <age>20</age> 
        <phone>1324525255</phone>
     </student> 
     <student>
        <name> 小虎 </name>
        <age>20</age> 
        <phone>1324525255</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\":\"kallen\",\"age\":\"26\",\"sex\":\"男\"},{\"name\":\"alex\",\"age\":\"24\",\"sex\":\"男\"}]";
   NSArray *arr = [str JSONValue];
   NSLog(@"%@",arr);



你可能感兴趣的:(IOS 网络解析(XML,JSON))