i want to return all the hyperlinks in a html. what would be the XPath Query that ?(Objective C)
Asked
Active
Viewed 417 times
1 Answers
0
You can use next sample for your task
NSData *data = [inputString dataUsingEncoding:NSUTF8StringEncoding];
xmlDocPtr doc = xmlReadMemory([data bytes], [data length], "", NULL, XML_PARSE_RECOVER);
xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression(BAD_CAST("//a"), xpathCtx);
if (xpathObj && xpathObj->nodesetval) {
for (int i = 0; i < xpathObj->nodesetval->nodeNr; ++i) {
xmlNodePtr node = xpathObj->nodesetval->nodeTab[i];
xmlChar *hrefProp = xmlGetProp(node, BAD_CAST("href");
xmlChar *content = xmlNodeGetContent(node);
NSString *hrefString = [NSString stringWithUTF8String:(char *)hrefProp];
NSString *contentString = [NSString stringWithUTF8String:(char *)content];
xmlFree(hrefProp);
xmlFree(content);
NSLog(@"Anchor %@, Content: %@", hrefString, contentString);
}
xmlXPathFreeContext(xpathCtx);
xmlXPathFreeObject(xpathObj);
xmlFreeDoc(doc);
For setting up libxml2 read carefully section Setting up your project file. Also you can download working sample from site and compile.

Victor
- 3,497
- 3
- 39
- 51
-
is this using libxml2.2 and objective c? – saleh Hosseinkahni Nov 29 '11 at 06:41
-
Also you can read the great article about using libxml2 in objective-c http://cocoawithlove.com/2008/10/using-libxml2-for-parsing-and-xpath.html – Victor Nov 29 '11 at 06:50
-
thank you so much. i visited that website, could u plz help me how should i send query for hyperlinks using those methods that ? – saleh Hosseinkahni Nov 29 '11 at 13:23
-
actually i am new into this topic, i dont know what lib to add to the headers and how to get the links in an Array, could you plz give me a complete sample? i will be so thankful. – saleh Hosseinkahni Nov 29 '11 at 16:23
-
@SalehHosseinkhani stop asking people to do your work for you. Victor has given you a lot of help here, providing code and an additional resource for help on setting up libxml2. Instead of asking him to do your job, you should **learn** from this code so that you understand how it works. Or are you just going to get everyone else to write your app for you? – Jasarien Nov 30 '11 at 10:20