Search code examples
iphoneobjective-cxmlparsinggdataxml

iPhone - difference between GDataXMLNode and GDataXMLElement, and how to use them


As the google doc is not available anymore, I'm lost with those concepts.

What is a node, and what is an element (that inherits the node) ?

How can I switch from nodes to elements. I mean, for example, if I write :

NSError* error;
NSData* xmlData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ForTesting" ofType:@"xml"]];

error = nil;
GDataXMLDocument* XMLDoc = [[[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error] autorelease];
if (XMLDoc == nil) {
    NSLog(@"%@", error.description);
    return;
}

GDataXMLNode* xmlElement = [[XMLDoc nodesForXPath:@"//root/fileVersion" error:nil] objectAtIndex:0];
NSString* fileVersion = xmlElement.stringValue;

GDataXMLNode* xmlList = [[XMLDoc nodesForXPath:@"//root/list" error:nil] objectAtIndex:0];  // single item

After that code, how can I write something like that to switch to GDataXMLElement instead of continuing with GDataXMLNode, that would requires me to continue using XPath (I don't want to use it past that point) :

// code don't work : elementsForName is not defined for GDataXMLNode
for (GDataXMLElement* xmlObject in [xmlList elementsForName:@"object"]) {
    MyClass* obj = [[[MyClass alloc] initWithXMLElement:xmlObject] autorelease];
}

Solution

  • GDataXMLNode is obviously the classes you use for XML parser- GDataXMLNode.h/.m

    In the code you have given returns an array. You can use.

    NSArray *myArray = [XMLDoc nodesForXPath:@"//root/fileVersion" error:nil];

    You can iterate myArray like this.

    for (GDataXMLElement *nodeXmlElt in myArray)
    {
        //some code
    }
    

    Each of my nodeXmlElt will be like given below.

    <fileVersion>
    <title>San Francisco CBS News</title>
    <link>http://news.google.com/news/</link>
    <fileVersion>
    
    //getting title
    NSArray *elementArray = [nodeXmlElt elementsForName:@"title"];
    GDataXMLElement *gdataElement = (GDataXMLElement *)[elementArray objectAtIndex:0];
    NSString *title = gdataElement.stringValue; //returns 'San Francisco CBS News'