-3

我想返回 html 中的所有超链接。什么是 XPath 查询?(目标 C)

4

1 回答 1

0

您可以将下一个示例用于您的任务

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);

要设置 libxml2,请仔细阅读设置项目文件部分。您也可以从站点下载工作示例并进行编译。

于 2011-11-29T06:38:53.007 回答