I have a web server which returns an XML file. Lets say http://ww开发者_如何学Pythonw.foo.bar/foo.php?wantXML=1
How would I fetch that file from the server and then parse it to access the data? I guess I would have to spawn a new thread and do the whole thing in the background to not block the UI? What classes must I look at?
SeismicXML sample from Apple is exaclty what you are looking for.
You can attempt to do:
- String manipulations
- XPATH
Id opt for xpath in all but the most simple cases - and even in those, you can't argue against xpath. Im not sure of the libraries though, but I know libXML is written in C and supported on the iphone.
For string manipulations, you can use the NS* family of methods.(substringFromIndex, substringToIndex, etc) And don't forget: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/Reference/Reference.html
Big Nerd Ranch, 'Parsing XML in Cocoa': http://weblog.bignerdranch.com/?p=48
To pull down XML or other stuff over http I recommend looking into using ASIHTTPRequest
Feel free to have a look at my convenient classes I created to parse simple XML documents like you can get from Nike+. Link
Basically the usage is as follows
NameValueParser *parser = [NameValueParser parser];
[parser addFieldName:@"screenName"]; // Name
[parser addFieldName:@"rank"]; // Position
[parser addFieldName:@"progress"]; // Distance
[parser parseData:data];
NSLog(@"%@", [parser list]); // Lets see what we got
I've used two approaches: NSXMLParser for simple and small files, and libxml for larger files. But there are libraries such as TouchXML that can simplify the process as well.
Basically, if you have a small data set, in memory DOM processing can work fine. But in a device such as the iPhone, you're better off using SAX-based parsers such as libxml2.
When you need to load the data:
[self performSelectorInBackground:@selector(LoadYourData) withObject:nil];
will not block the main UI thread.
For libxml2, you will need to implement C callbacks to process the chunks of data coming in from a NSURLConnection.
精彩评论