views:

465

answers:

3

Hello, I have a NSString with this content:

<?xml version="1.0" encoding="UTF-8"?>
<rsp stat="ok">
 <mediaid>y2q62</mediaid>
 <mediaurl>http://twitpic.com/url&lt;/mediaurl&gt;
</rsp>

Now I want to get the twitpic-Url in a new NSString without all the other Strings. How can I make this? Can I search in NSStrings? Like: Find the strings between the Strings ? Or can I find directly URLs in a NSString?

Thanks for your help!

+5  A: 

Sounds like you need to parse XML files. Here is a good tutorial Objective C has some good XML parsing functions.

iPhone Guy
It is not a xml, it just has the content like a xml.
Flocked
@Flocked - it is absolutely XML. You can't get any more XML than the XML snipped stored in your NSString that you showed in the question.
Jason Coco
Yep, although parsing with an regexp seems much easier and a lot faster HTML/XML will always burn you in the long run...
Niels Castle
Hehehhehe... and regexes don't burn you in the long run? Seriously, if it is XML parse it like XML.
bbum
A: 

Use NSXMLParser after converting the string to NSData.

ergosys
+5  A: 

Use a regex: RegexKitLite

Here's a complete example using the HTTP matching URL from the RegexKitLite documentation. The RegexKitLite -componentsMatchedByRegex: method will return a NSArray of all the URL matches it finds in the string.

#import <Foundation/Foundation.h>
#import "RegexKitLite.h"

int main(int argc, char *argv[]) {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

  NSString *stringToSearch =
    @"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
    @"<rsp stat=\"ok\">\n"
    @" <mediaid>y2q62</mediaid>\n"
    @" <mediaurl>http://twitpic.com/url&lt;/mediaurl&gt;\n"
    @"</rsp>\n";

  NSString *urlRegex = @"\\bhttps?://[a-zA-Z0-9\\-.]+(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?";

  NSArray *matchedURLsArray = [stringToSearch componentsMatchedByRegex:urlRegex];

  NSLog(@"matchedURLsArray: %@", matchedURLsArray);

  [pool release];
  pool = NULL;

  return(0);
}

Compile and run with:

shell% gcc -arch i386 -o url url.m RegexKitLite.m -framework Foundation -licucore
shell% ./url
2010-01-14 16:05:32.874 url[71582:903] matchedURLsArray: (
    "http://twitpic.com/url"
)
johne