使用GDataXMLDocument解析xml属性

时间:2011-09-08 11:22:56

标签: iphone objective-c xml xcode parsing

如何使用GDataXMLDocument解析xml属性?

我有一个xml字符串作为NSData(名为xmlData)

<students>
 <student>
       <name>Raju</name>
       <age>25</age>      
 </student>
</students>

然后我读了它:

 NSError *error;

 GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
    if (doc == nil) { return ; }


    //NSArray *partyMembers = [doc.rootElement elementsForName:@"Player"];
    NSArray *partyMembers = [doc nodesForXPath:@"//students/student" error:nil];
    for (GDataXMLElement *partyMember in partyMembers) {

        // Let's fill these in!
        NSString *name;
        int age;


        // Name
        NSArray *names = [partyMember elementsForName:@"name"];
        if (names.count > 0) {
            GDataXMLElement *firstName = (GDataXMLElement *) [names objectAtIndex:0];
            name = firstName.stringValue;
   NSLog([NSString stringWithFormat:@"name is: %@",name]);
        } else continue;

        // Level
        NSArray *ages = [partyMember elementsForName:@"age"];
        if (ages.count > 0) {
            GDataXMLElement *firstLevel = (GDataXMLElement *) [ages objectAtIndex:0];
            age = firstLevel.stringValue.intValue;
   NSLog([NSString stringWithFormat:@"age  is: %d",age]);
        } else continue;

    }

    [doc release]; 

}

我获得名称年龄

现在我有一个带有属性的xml(作为NSData)。

<students>
 <student name="Raju" age = 25>       

 </student>
</students>

如何使用GDataXMLDocument阅读年龄和姓名?

2 个答案:

答案 0 :(得分:5)

NSString *name = [[partyMember attributeForName:@"name"] stringValue];

答案 1 :(得分:1)

NSInteger type=[[(GDataXMLNode *)[[urls objectAtIndex:i] attributeForName:@"type"] stringValue] intValue];


NSInteger bit_stream=[[(GDataXMLNode *) [[urls objectAtIndex:i] attributeForName: @"bit_stream"] stringValue] intValue];