2012年6月21日 星期四

在iOS上使用html parser

這裡是使用libxml2與hpple來做html parser。

1. 必須先將libxml2加到專案裡,可參考以下連結教學
http://justcoding.iteye.com/blog/1474176

2. 將hpple framework加到專案裡,
   下载hpple from https://github.com/topfunky/hpple
   加入以下檔案:HTFpple.h HTFpple.m HTFppleElement.h HTFppleElement.m XPathQuery.h XPathQuery.m

   NSString *htmlString=[NSString stringWithContentsOfURL:[NSURL URLWithString: @"http://ebook.sunlight.tw/"] encoding: NSUTF8StringEncoding error:nil];          NSData *htmlData=[htmlString dataUsingEncoding:NSUTF8StringEncoding];      TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];   
    NSArray *elements  = [xpathParser searchWithXPathQuery:@"/html/body/pre/a"]; // get the title    
    TFHppleElement *element  = [xpathParser peekAtSearchWithXPathQuery:@"/html/body/pre/a"];
    TFHppleElement *element2  = [xpathParser peekAtSearchWithXPathQuery:@"/html/body/pre/a[2]"];
    NSString *elementContent = [element objectForKey:@"href"];
  
    NSLog(@"result = %@",element);
     NSLog(@"result = %@",element2);
    NSLog(@"result = %@",[element attributes]);
    NSLog(@"result = %@",[element2 attributes]);

沒有留言: