views:

234

answers:

3

I know that when parsing XML with objective-c most of the time you use NSXMLParser. But what if you only need to read one element. Using NSXMLParser sounds like an overload to me.

The issue is that flickr API doesn't use JSON as response when uploading an image. So my response now is:

<rsp stat="ok">
<photoid>4638598522</photoid>
</rsp>

I only need to know the photoid and I like to know what the best solution will be for this.

A: 

Treat the xml as a string and use a regular expression to extract the element you want. Perhaps with the RegexKitLite library. You can create the regular expression with help from gskinner's online regex tool.

possibly just with this :

([0-9])
Ross
XML parsing with regular expressions? Hmmm...
dreamlax
it's not really xml parsing when you are only looking to extract one attribute. I would describe it as screen scraping.
Ross
Yeah. and in this case probably it would work always
Marko
I'd like to see you parse <element>foobar<nested>something</nested> <!-- </element> --></element> with regular expressions.
Mike Weller
@Mike: do you mean me? I am no regular expression expert but experts I do use.
Ross
@mike in this case it is just an simple xml string. So parsing with NSXMLParser sounds (and i think it is) overkill
Marko
OK I see you added an example of the xml. So yeah I guess regular expressions might be OK in this case.
Mike Weller
A: 
int main(int argc, char* argv[]){
    int num;
    if (argc < 2) return -1;
    printf("arg: %s", argv[1]);
    sscanf(argv[1], "id>%d</", &num);
    printf("result: %i", num);
    if (result < 0) return -1;
    return 0;
}

Simply use sscanf. It should do the trick just fine. (I think NSString has a similar method, if not you can grab the c char array from it then pass it back).

CodeJoust
I was searching a little bit more on stackoverflow and found this link: http://stackoverflow.com/questions/594797/how-to-use-nsscanner.For me that does do the trick. thanks for putting me in the right direction
Marko
A: 

Here are the two lines of code to get the photoid:

NSString *source = @"<rsp stat=\"ok\"><photoid>4638598522</photoid></rsp>";
NSLog(@"photoid: %@", [[[[source componentsSeparatedByString:@"<photoid>"] objectAtIndex:1] componentsSeparatedByString:@"</photoid>"] objectAtIndex:0]);
sfa
Thanks. I already had it fixed but I this solution is better.
Marko