Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9293181
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T21:04:21+00:00 2026-06-18T21:04:21+00:00

This is my method body for parsing img src image links from poorly formed

  • 0

This is my method body for parsing “img src” image links from poorly formed html generated by an RSS feed… I am aware that NSXML only parses XML, but I have this hope that it can stumble through the mess to find these miniscule image links from messy html.

I’m trying to retrieve ONLY the FIRST image link found in the src attribute I find in each element name called IMG in nsData that has a src attribute and then save it to a NSString *img in another class. The img tags are not all the same, for instance an instance of nsData will contain only one image instance like any one of these:

< img class=”ms-rteStyle-photoCredit” src=”www.imagelinkthatineed.com” stuff I don’t need

< img alt=”” src=”www.imagelinkineedfortableimagecellpreview” stuff I don’t need

< img class=”ms-rteStyle-photoCredit” src=”www.IneedThisLink.com” more stuff I don’t need

The only class that seems to generate NSLog output is the first one.

How can I get the parser methods to actually run ?

Given that there’s a way, is there a different, simpler way you recommend?

#import "HtmlParser.h"
#import "ArticleItem.h"

@implementation HtmlParser
@synthesize elementArray;

- (HtmlParser *) InitHtmlByString:(NSString *)string {
//    NSString *description = [NSString string];
NSData *nsData = [[NSData alloc] initWithContentsOfFile:(NSString *)string];
elementArray = [[NSMutableArray alloc] init];
parser = [[NSXMLParser alloc] initWithData:nsData];
parser.delegate = self;
[parser parse];

If I NSLog(@”%@”, nsData); in this method body, the output spits out the raw HTML.

currentHTMLElement = [ArticleItem alloc];
return self;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"img src"]) {
    currentHTMLElement = [[ArticleItem alloc] init];
}
NSLog(@"\t%@ found a %@ element", self, elementName);
}
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (!currentHTMLElement)
    currentHTMLElement = [[NSMutableString alloc] initWithString:string];   
NSLog(@"Processing Value: %@", currentHTMLElement);
}
- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName   
{
if ([elementName isEqualToString:@"img src"])
    {
        currentHTMLElement.img = elementName;
        [elementArray addObject:currentHTMLElement];
        currentHTMLElement = nil;
        currentNodeContent = nil;
    }
else
{
    if (currentHTMLElement !=nil && elementName != nil && ([elementName isEqualToString:@"img src"]))
    {
        [currentHTMLElement setValue:currentHTMLElement forKey:elementName];
    }
}
    currentHTMLElement = nil;
}                
@end

Thank you for your thoughts.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T21:04:22+00:00Added an answer on June 18, 2026 at 9:04 pm

    Given that HTML is generally not well-formed XML, NSXMLParser might not work. If you want to parse HTML, you might refer to this Ray Wenderlich article, How to Parse HTML on iOS. If you’ve followed those instructions and have added Hpple to your project, you can then retrieve the image src attributes like so:

    #import "TFHpple.h"
    
    - (void)retrieveImageSourceTagsViaHpple:(NSURL *)url
    {
        NSData *data = [NSData dataWithContentsOfURL:url];
    
        TFHpple *parser = [TFHpple hppleWithHTMLData:data];
    
        NSString *xpathQueryString = @"//img";
        NSArray *nodes = [parser searchWithXPathQuery:xpathQueryString];
    
        for (TFHppleElement *element in nodes)
        {
            NSString *src = [element objectForKey:@"src"];
            NSLog(@"img src: %@", src);
        }
    }
    

    Alternatively, and I say this bracing myself for the onslaught of anti-NSRegularExpression responses (in the vein of my all-time favorite Stack Overflow answer), if you want a list of img tags in an html file, you can use the following somewhat complicated regular expression:

    - (void)retrieveImageSourceTagsViaRegex:(NSURL *)url
    {
        NSString *string = [NSString stringWithContentsOfURL:url
                                                    encoding:NSUTF8StringEncoding
                                                       error:nil];
    
        NSError *error = NULL;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(<img\\s[\\s\\S]*?src\\s*?=\\s*?['\"](.*?)['\"][\\s\\S]*?>)+?"
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                 error:&error];
    
        [regex enumerateMatchesInString:string
                                options:0
                                  range:NSMakeRange(0, [string length])
                             usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
    
                                 NSString *src = [string substringWithRange:[result rangeAtIndex:2]];
                                 NSLog(@"img src: %@", src);
                             }];
    }
    

    If you wanted to use NSXMLParser, it would look like so:

    - (void)retrieveImageSourceTagsViaNSXMLParser:(NSURL *)url
    {
        NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
        parser.delegate = self;
        [parser parse];
    }
    
    #pragma mark - NSXMLParserDelegate methods
    
    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
    {
        if ([elementName isEqualToString:@"img"])
        {
            NSString *src = attributeDict[@"src"];
    
            NSLog(@"img src: %@", src);
        }
    }
    

    The problem is, in my experience, NSXMLParser is less successful in parsing HTML than LibXML2/Hpple is. I find that on some simple pages, the above works great. But in other situations, it doesn’t. Bottom line, While NSXMLParser is great at parsing well-formed XML, I’d be wary of using it for the parsing of HTML.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a problem, I need to change body of method when this class
Given this method to work on a HTML page in a webbrowser: bool semaphoreForDocCompletedEvent;
I am following the well famous IBM tutorial on parsing an RSS feed. I
This method right below reverses a doubly linked list with n elements. I dont
This method works as expected - it creates a JTree with a root node
This method that draws my tiles seems to be quite slow, Im not sure
This method is working totally right in matlab. but, when I compiled it in
This is my javascript method in .aspx file. I want to invoke this method
With this method declaration (no overloads): void Method(double d) { // do something with
Take this method /** * @return List of group IDs the person belongs to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.