Parse HTML iPhone

后端 未结 3 541
孤独总比滥情好
孤独总比滥情好 2020-12-10 09:39

I have a .html file on a server, which I need to parse info from. It´s nothing huge it´s just




some text

<
相关标签:
3条回答
  • 2020-12-10 10:15

    Use UIwebView in your tableViewCell. Or I suggest use three20 Framework's TTStyleLabel. It will display html properly parsed.

    0 讨论(0)
  • 2020-12-10 10:20

    Rather than encourage you to figure out how best to parse the HTML, may I suggest just leaving a static JSON file on your web server instead? There are many JSON parser libraries available for iOS that will allow you to get the data you need.

    A side effect from doing this is that you will use less bandwidth in the download, it will be faster to parse, and the resulting code will be less brittle to changes in your data payload.

    0 讨论(0)
  • 2020-12-10 10:34

    You can parse it with libxml, here is a sample I wrote it for you:

    #import <Foundation/Foundation.h>
    #import <libxml/HTMLTree.h>
    #import <libxml/HTMLparser.h>
    #import <libxml/xpath.h>
    
    @interface NSString(HTMLParser)
    - (NSArray *)resultWithXPath:(NSString *)xpath;
    @end
    
    @implementation NSString(HTMLParser)
    
    - (NSArray *)resultWithXPath:(NSString *)xpath
    {
      htmlDocPtr doc = htmlParseDoc((xmlChar *)[[self dataUsingEncoding:NSUTF8StringEncoding] bytes], "UTF-8");
      xmlXPathContextPtr context = xmlXPathNewContext(doc);
      xmlXPathObjectPtr xpathobj = xmlXPathEvalExpression(BAD_CAST [xpath UTF8String], context);
      xmlNodeSetPtr nodeset = xpathobj->nodesetval;
      if (xmlXPathNodeSetIsEmpty(nodeset))
        return nil;
    
      NSMutableArray *result = [[NSMutableArray alloc] initWithCapacity:nodeset->nodeNr];
    
      for (int i=0; i<nodeset->nodeNr; i++){
        xmlNodePtr node = nodeset->nodeTab[i];
        [result addObject:[NSString stringWithCString:(char *)xmlNodeGetContent(node) encoding:NSUTF8StringEncoding]];
      }
    
      xmlXPathFreeObject(xpathobj);
      xmlXPathFreeContext(context);
      xmlFreeDoc(doc);
    
      return [result autorelease];
    }
    
    @end
    
    int main (int argc, const char * argv[])
    {
      NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
      NSString *html = @"<html>\
      <body>\
      <p> some text </p>\
      <p> some other text </p>\
      </body>\
      </html>";
    
      NSArray *result = [html resultWithXPath:@"//p"];
      NSLog(@"result: %@", result);
      [pool release];
    
      return 0;
    }
    
    0 讨论(0)
提交回复
热议问题