XML parsing in Cocoa Touch / iPhone

Ok, I saw TouchXML, parseXML, NSXMLDocument, NSXMLParser, but I'm really confused about what to do.

I have an iphone application that connects to servers, requests data and receives an XML response. A sample xml response for different requests is set at http://pastebin.com/f681c4b04

I have other classes that act like Controller (like in MVC to execute data fetch logic). This class receives input from View classes and processes it, for example. send a request to the web server, receive xml, parse the xml, fill in its variables (its singleton / common classes), and then the answers as true or false for the caller. Caller, based on the response given by the controller class, checks the controller variables and displays the corresponding content to the user.

I have the following controller class variables:

@interface backendController : NSObject { NSMutableDictionary *searchResults, *plantInfoResults, *bookmarkList, *userLoginResult; } 

and functions like getBookmarkList, getPlantInfo. Right now I am printing a normal XML return by the NSLog web server (@ "Result ::% @" [NSString stringWithContentsOfURL: url])

I want the generic function that receives the XML returned from the server to process it, make it an NSMutableDictionary containing the textual representation of the XML opening tags as Keys values ​​and the XML Tag as values ​​and returning this.

Just one question, how to do this?

+4
source share
3 answers

Have you tried any of the XML parsers that you talked about? This is how they set the key value of the node name:

 [aBook setValue:currentElementValue forKey:elementName]; 

PS Double check your XML, it seems you are missing the root node for some of your results. If you do not leave it for simplicity.

Take a look at the w3schools XML tutorial , it should point you in the right direction for XML syntax.

+4
source

Consider the following code snippet that uses libxml2 , Matt Gallagher libxml2, and Ben Copsey ASIHTTPRequest to parse an HTTP document.

To PerformXMLXPathQuery XML, use PerformXMLXPathQuery instead of PerformHTTPXPathQuery , which I use in my example.

An instance of nodes type NSArray * will contain NSDictionary * objects that you can analyze recursively to get the data you need.

Or, if you know the schema of your XML document, you can write an XPath query to directly get the value of nodeContent or nodeAttribute .

 ASIHTTPRequest *request = [ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://stackoverflow.com/"]; [request start]; NSError *error = [request error]; if (!error) { NSData *response = [request responseData]; NSLog(@"Root node: %@", [[self query:@"//" withResponse:response] description]); } else @throw [NSException exceptionWithName:@"kHTTPRequestFailed" reason:@"Request failed!" userInfo:nil]; [request release]; ... - (id) query:(NSString *)xpathQuery withResponse:(NSData *)respData { NSArray *nodes = PerformHTMLXPathQuery(respData, xpathQuery); if (nodes != nil) return nodes; return nil; } 
0
source

provides you with one simple example of parsing XML in a table, hope it helps you.

//XMLViewController.h

 #import <UIKit/UIKit.h> @interface TestXMLViewController : UIViewController<NSXMLParserDelegate,UITableViewDelegate,UITableViewDataSource>{ @private NSXMLParser *xmlParser; NSInteger depth; NSMutableString *currentName; NSString *currentElement; NSMutableArray *data; } @property (nonatomic, strong) IBOutlet UITableView *tableView; -(void)start; @end 

//TestXMLViewController.m

 #import "TestXmlDetail.h" #import "TestXMLViewController.h" @interface TestXMLViewController () - (void)showCurrentDepth; @end @implementation TestXMLViewController @synthesize tableView; - (void)start { NSString *xml = @"<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Node><name>Main</name><Node><name>first row</name></Node><Node><name>second row</name></Node><Node><name>third row</name></Node></Node>"; xmlParser = [[NSXMLParser alloc] initWithData:[xml dataUsingEncoding:NSUTF8StringEncoding]]; [xmlParser setDelegate:self]; [xmlParser setShouldProcessNamespaces:NO]; [xmlParser setShouldReportNamespacePrefixes:NO]; [xmlParser setShouldResolveExternalEntities:NO]; [xmlParser parse]; } - (void)parserDidStartDocument:(NSXMLParser *)parser { NSLog(@"Document started"); depth = 0; currentElement = nil; } - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { NSLog(@"Error: %@", [parseError localizedDescription]); } - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { currentElement = [elementName copy]; if ([currentElement isEqualToString:@"Node"]) { ++depth; [self showCurrentDepth]; } else if ([currentElement isEqualToString:@"name"]) { currentName = [[NSMutableString alloc] init]; } } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:@"Node"]) { --depth; [self showCurrentDepth]; } else if ([elementName isEqualToString:@"name"]) { if (depth == 1) { NSLog(@"Outer name tag: %@", currentName); } else { NSLog(@"Inner name tag: %@", currentName); [data addObject:currentName]; } } } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if ([currentElement isEqualToString:@"name"]) { [currentName appendString:string]; } } - (void)parserDidEndDocument:(NSXMLParser *)parser { NSLog(@"Document finished", nil); } - (void)showCurrentDepth { NSLog(@"Current depth: %d", depth); } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. data = [[NSMutableArray alloc]init ]; [self start]; self.title=@ "XML parsing"; NSLog(@"string is %@",data); } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { `enter code here`return [data count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *simpleTableIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier]; } cell.textLabel.text = [data objectAtIndex:indexPath.row]; return cell; } @end 
0
source

All Articles