Parsing using GDataXML with XPATH

652 views Asked by At

I have an XML file with multiple entry nodes:

<entry>
    <published>2013-12-19T13:30:20-05:00</published>
    <title>This is a title</title>
    <content type="html">This is the content</content>
    <author>
        <name>Valentina</name>
    </author>
</entry>

I am trying to parse it using XPath(for learning purpose) but I can't seem to make it work. I have the following code:

        NSData* xmlData = [[NSMutableData alloc] initWithContentsOfURL:[NSURL URLWithString:link]];
        GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:nil];

        NSArray* entries = [document.rootElement elementsForName:@"entry"];
        for(GDataXMLElement* element in entries)
        {
            published = [element nodesForXPath:@"/entry/published" error:nil][0];
        }

I always get an error with index 0 beyond bounds for empty array when trying to get the published node text. I tried different things but can't figure it out what is the correct way.
Entries array contains 10 entry nodes.

1

There are 1 answers

0
Jens Erat On BEST ANSWER

The XPath is evaluated from the current context, which already is an <entry/> element. Change the XPath expression to ./published or even just published.

published = [element nodesForXPath:@"published" error:nil][0];

But why use XPath at all if you just want to query a child node?

published = [element elementsForName:@"published"][0];