开发者

iPhone Options for reading item from XML?

开发者 https://www.devze.com 2022-12-23 05:30 出处:网络
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 t

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开发者_如何学C 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


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


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.


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)
}
0

精彩评论

暂无评论...
验证码 换一张
取 消