views:

43

answers:

3

I am accessing this data from a web server using NSURL, what I am trying to decide is should I read this as XML or should I just use NSScanner and rip out the [data] bit I need. I have looked around the web for examples of extracting fields from XML on the iPhone but it all seems a bit overkill for what I need. Can anyone make any suggestions or point me in the right direction. In an ideal world I would really like to just specify [data] and get a string back "2046 3433 5674 3422 4456 8990 1200 5284"

<!DOCTYPE tubinerotationdata>
<turbine version="1.0">
<status version="1.0" result="200">OK</status>
<data version="1.0">
    2046 3433 5674 3422 4456 8990 1200 5284
</data>
</turbine>

any comments / ideas are much appreciated.

gary

+2  A: 

You should always parse XML with an XML parser. There are no guarantees on ordering and other things that will break your code eventually. Parsing with a real XML parser is the only way to be sure that your code won't break when the input changes.

fuzzy lollipop
For data that simple, I don't think you need to use an XML parser necessarily. Yes, there are situations where you can protect yourself from having to rewrite code by using a proper parser, but the data file provided doesn't seem like an obvious example of that. For one, it doesn't have a schema or any clue as to whether the structure of the data will change with the version number. It seems to me that your chances of having to rewrite code when the feed changes are just about even between an XML parser and something like a regex library or NSScanner.
Victorb
A: 

For simple data tasks like this I use RegexKitLite which is a light-weight regex library for iPhone. A basic implementation might look like this (assuming the contents of your file are in NSString *XMLString)

NSString *regex = @"<data\\s+version=\"(\\d+\\.\\d+)\">([^<]+)<\\/data>";
NSArray *components = [XMLString arrayOfComponentsMatchingRegex:regex];
if (components.count == 3) {
  // [components objectAtIndex:0] contains the full match
  // [components objectAtIndex:1] contains the version number
  // [components objectAtIndex:2] contains the contents of the data tag
  //                              (including leading/trailing whitespace)
}
Victorb
+2  A: 

Personally, I would use NSXMLParser so that you have everything in place in case you want to extract more information from the XML file.

mmoris