我一直在使用xpath規範XPath Introduction
通過將HTML從URL傳遞到NSXMLDocument和t母雞得到我想要的值NSXMLNode'snodesForXPath:error:
在這種情況下,我使用大型機的URL。但任何有效的網址都應該可以。
兩個NSXML類似乎沒有問題解析HTML就像他們做XML
有大量的XPath查詢字符串語法例子,你可以搜索,我發現它是非常容易深入到DOM樹一旦你知道HTML標籤和類語法是什麼。
我已經使用了一個非常簡單的a href在這裏查詢整個頁面。
但我已經加入了一個註釋掉的例子來顯示更多。上述
-(void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[theWebView setFrameLoadDelegate:self];
NSURL* fileURL = [NSURL URLWithString:@"http://example.com"];
NSURLRequest* request = [NSURLRequest requestWithURL:fileURL];
[[theWebView mainFrame] loadRequest:request];
}
-(void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
NSError *err_p = nil;
NSXMLDocument * xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:[NSURL URLWithString:[theWebView mainFrameURL]]
options:(NSXMLNodePreserveWhitespace|
NSXMLNodePreserveCDATA)
error:&err_p];
if (xmlDoc == nil) {
xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:[NSURL URLWithString:[theWebView mainFrameURL]]
options:NSXMLDocumentTidyXML
error:&err_p];
}
NSError * error2;
NSString *xpathQueryTRTest [email protected]"//a";//--query string for all <a href tags
//-- for example 2 --NSString *xpathQueryTRTest [email protected]"//div/p[1]";//--query string for all <a href tags
NSArray *newItemsNodesTRTEST = [xmlDoc nodesForXPath:xpathQueryTRTest error:&error2];//--xpath node results returned in an array
[xmlDoc release];
if (error2)
{
[[NSAlert alertWithError:error2] runModal];
return ;
}
for (NSXMLElement *node in newItemsNodesTRTEST)//--parse the nodes in the array
{
NSLog(@"\nThe Node = %@\nThe node href value = %@", node, [[node attributeForName:@"href"]stringValue]);
//--for example 2 -- NSLog(@"\nThe Node value = %@\n", [node stringValue]);
}
}