ios GDataXMLNode 操作xml

阅读更多

 创建XML:

 

//创建XML

    GDataXMLElement *rootElement = [GDataXMLNode elementWithName:@"request"];

    GDataXMLElement *element = [self getElementWithName:@"peter" withAge:@"24" withSex:@"male"withAttribute:@"0"];

    [rootElement addChild:element];

    element = [self getElementWithName:@"Green" withAge:@"26" withSex:@"female"withAttribute:@"1"];

    [rootElement addChild:element];

    element = [self getElementWithName:@"Susan" withAge:@"28" withSex:@"female"withAttribute:@"1"];

    [rootElement addChild:element];

    GDataXMLDocument *document = [[GDataXMLDocument alloc]initWithRootElement:rootElement];

    NSData *data =  [document XMLData];

    NSString *content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(content);

 

 

解析xml

   NSData *xmlData = [xml dataUsingEncoding:NSUTF8StringEncoding];

    //使用NSData对象初始化

    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData  options:0 error:nil];

    

    //获取根节点(Users)

    GDataXMLElement *rootElement = [doc rootElement];

    

    GDataXMLElement *nameElement = [[rootElement elementsForName:@"RSPCOD"] objectAtIndex:0];

    NSString *name = [nameElement stringValue];

    NSLog(@"RSPCOD name is:%@",name);

    

    GDataXMLElement *trandetailsElement = [[rootElement elementsForName:@"TRANDETAILS"] objectAtIndex:0];

    

    //获取根节点下的节点(User)

    NSArray *users = [trandetailsElement elementsForName:@"TRANDETAIL"];

    

    for (GDataXMLElement *user in users) {

      

                    //User节点的id属性

            NSString *userId = [[user elementsForName:@"BRAACTNO"] objectAtIndex:0];

            NSLog(@"User id is:%@",userId);

            

            //获取name节点的值

            GDataXMLElement *nameElement = [[user elementsForName:@"MERNAM"] objectAtIndex:0];

            NSString *name = [nameElement stringValue];

            NSLog(@"User name is:%@",name);

            

            //获取age节点的值

            GDataXMLElement *ageElement = [[user elementsForName:@"OPNBNK"] objectAtIndex:0];

            NSString *age = [ageElement stringValue];

            NSLog(@"User age is:%@",age);

            NSLog(@"-------------------");

        

 

    }

  • GDataXMLNode.zip (15.6 KB)
  • 下载次数: 5

你可能感兴趣的:(ios GDataXMLNode 操作xml)