Skip to content

Commit

Permalink
simple xpath only from root document
Browse files Browse the repository at this point in the history
  • Loading branch information
neocoin committed Jun 21, 2011
1 parent c0c9b95 commit 78ad7c0
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
2 changes: 2 additions & 0 deletions HTMLNode.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ typedef enum
//Finds all children with a matching attribute
-(NSArray*)findChildrenWithAttribute:(NSString*)attribute matchingName:(NSString*)className allowPartial:(BOOL)partial;

-(NSArray*)nodesForXPath:(NSString*)xpath;

//Gets the attribute value matching tha name
-(NSString*)getAttributeNamed:(NSString*)name;

Expand Down
46 changes: 46 additions & 0 deletions HTMLNode.m
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@

#import "HTMLNode.h"
#import <libxml/HTMLtree.h>
#import <libxml/xpath.h>
#import <libxml/xpathInternals.h>


@implementation HTMLNode

Expand Down Expand Up @@ -409,4 +412,47 @@ -(NSString*)rawContents {
return rawContentsOfNode(_node);
}

-(NSArray*)nodesForXPath:(NSString*)query{
xmlDocPtr doc = _node->doc;

xmlXPathContextPtr xpathCtx;
xmlXPathObjectPtr xpathObj;

/* Create xpath evaluation context */
xpathCtx = xmlXPathNewContext(doc);
if(xpathCtx == NULL)
{
NSLog(@"Unable to create XPath context.");
return nil;
}

/* Evaluate xpath expression */
xpathObj = xmlXPathEvalExpression((xmlChar *)[query cStringUsingEncoding:NSUTF8StringEncoding], xpathCtx);
if(xpathObj == NULL) {
NSLog(@"Unable to evaluate XPath.");
return nil;
}

xmlNodeSetPtr nodes = xpathObj->nodesetval;
if (!nodes)
{
NSLog(@"Nodes was nil.");
return nil;
}

NSMutableArray *resultNodes = [NSMutableArray array];
for (NSInteger i = 0; i < nodes->nodeNr; i++)
{
HTMLNode* node = [[[HTMLNode alloc] initWithXMLNode:nodes->nodeTab[i]] autorelease];
[resultNodes addObject:node];
}

/* Cleanup */
xmlXPathFreeObject(xpathObj);
xmlXPathFreeContext(xpathCtx);

return resultNodes;
}


@end

0 comments on commit 78ad7c0

Please sign in to comment.