Get tag value from XML string iphone

Sometimes, it is required to get value of tag from xml string which has limited tags.
suppose the xml string (say returnString) is
<success>1</success><title>Information</title><message>This is testing</message>
and we need to extract value of success, title and message tags.
See following method for this:

-(NSString *)getTagValue:(NSString *)xmlStr tagName:(NSString *)tagName 
 NSString *ret = @"";
 NSScanner *scanner = [[NSScanner alloc] initWithString:xmlStr];
 [scanner scanUpToString:[NSString stringWithFormat:@"<%@>",tagName] intoString:nil];
 [scanner scanString:[NSString stringWithFormat:@"<%@>",tagName] intoString:nil];
 [scanner scanUpToString:[NSString stringWithFormat:@"</%@>",tagName] intoString:&ret];
 @catch(NSException *ex)
  return ret;
We can extract title from the string:

[self getTagValue:returnString tagName:@"title"]

See following example to show message from the xml string(returnString):
UIAlertView *info;

if ([[self getTagValue:returnString tagName:@"success"] intValue]  == 1)
  info = [[UIAlertView alloc] initWithTitle:[self getTagValue:returnString tagName:@"title"] message:[self getTagValue:returnString tagName:@"message"] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[info show];
[info release];
Then it will show:

Hope, It helps.

No comments:

Post a Comment