Jump to content
Sign in to follow this  
mariobento

Search em NSString por tag's HTML

Recommended Posts

mariobento

Boas, neste momento tenho código que me permite obter o conteúdo que está entre uma determinada tag HTML, a questão é que no mesmo HTML há 2 tags com o mesmo nome (<description>) alguém sabe como obter apenas o valor da segunda tag?

segue o código!

// Determine "<description>" location
NSRange divRange = [html rangeOfString:@"<description>" options:NSCaseInsensitiveSearch];
if (divRange.location != NSNotFound)
{
 // Determine "</description>" location according to "<description>" location
 NSRange endDivRange;

 endDivRange.location = divRange.length + divRange.location;
 endDivRange.length = [html length] - endDivRange.location;
 endDivRange = [html rangeOfString:@"</description>" options:0 range:endDivRange];


 if (endDivRange.location != NSNotFound)
 {
	 // Tags found: retrieve string between them
	 divRange.location += divRange.length;
	 divRange.length = endDivRange.location - divRange.location;

	 NSString*TEST = [html substringWithRange:divRange];
	 NSLog(@"%@",TEST);
 }
}

Obrigado!

Share this post


Link to post
Share on other sites
KTachyon

Tens duas soluções mais elegantes que procurar ranges de uma NSString:

1. Utilizas um parser XML (ou qualquer outra opções que te permita trabalhar decentemente com o DOM).

2. Utilizas expressões regulares:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<description>(.*?)</description>" options:0 error:&error];
NSArray *matches = [regex matchesInString:x options:0 range:NSMakeRange(0, x.length)];

NSTextCheckingResult *secondResult = matches[1];
NSRange stringRange = [secondResult rangeAtIndex:1];

NSString *result = [x substringWithRange:stringRange];


“There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.”

-- Tony Hoare

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.