Search code examples
objective-cxpathhpple

XPath - Attributes selection


I have this code:

<p class='test'>
    Text1
</p>

<p class='test'>
    Text1
</p>

With Hpple (XPath), I need to read the first <p class='test'>, and the second, but I dont know how to do this.

Maybe like:

//p[@class='test'][1]
//p[@class='test'][2]

Thanks


Solution

  • Try this:

    #import "TFHpple.h"
    
    NSData  * data      = [NSData dataWithContentsOfFile:@"index.html"];
    TFHpple * doc       = [[TFHpple alloc] initWithHTMLData:data];
    NSArray * elements  = [doc search:@"//p[@class='test']"];
    
    TFHppleElement * element = [elements objectAtIndex:0];
    [e content];              // Tag's innerHTML
    [e tagName];              // "a"
    [e attributes];           // NSDictionary of href, class, id, etc.
    [e objectForKey:@"href"]; // Easy access to single attribute
    

    You have more elements so loop the 'elements' array, in this case you could do [elements objectAtIndex:0] and [elements objectAtIndex:1].