Parsing NSXMLNode Attributes in Cocoa

后端 未结 2 1630
名媛妹妹
名媛妹妹 2021-02-08 05:31

Given the following XML file:

    

 

        
2条回答
  •  醉酒成梦
    2021-02-08 05:53

    YES! I answered my own question somehow.

    When iterating through the XML document, instead of assigning each child node as an NSXMLNode, assign it as an NSXMLElement. You can then use the attributeForName function, which returns an NSXMLNode, to which you can use stringValue on to get the attribute's value.

    Since I'm bad at explaining things, here's my commented code. It might make more sense.

    //make sure that the XML doc is valid
    if (xmlDoc != nil) {
                //get all of the children from the root node into an array
                NSArray *children = [[xmlDoc rootElement] children];
                int i, count = [children count];
    
                //loop through each child
                for (i=0; i < count; i++) {
                    NSXMLElement *child = [children objectAtIndex:i];
    
                        //check to see if the child node is of 'movie' type
                        if ([child.name isEqual:@"movie"]) {
                        {
                            NSXMLNode *movieName = [child attributeForName:@"name"];
                            NSString *movieValue = [movieName stringValue];
    
                            //verify that the value of 'name' attribute of the node equals the value we're looking for, which is 'tc'
                            if ([movieValue isEqual:@"tc"]) {
                            //do stuff here if name's value for the movie tag is tc.
                            }
                        }
                }   
       }
    

提交回复
热议问题