XMLController
//
//  XMLParserViewController.m
//  XMLParser
//
//  Created by Santosh Raghavan on 11/18/10.
//  Copyright 2010 CMC. All rights reserved.
//
 
#import "XMLParserViewController.h"
 
@implementation XMLParserViewController
 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
 
-(NSInteger) tableView:(UITableView *) tv numberOfRowsInSection: (NSInteger) section {
    return [orders count];
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:"@test"];
 
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"test" ] autorelease];
    }
 
    int orderIndex = [indexPath indexAtPosition: [indexPath length] - 1];
    NSString *displayString = [[orders objectAtIndex: orderIndex] objectForKey: @"ordernumber"];
    displayString = [displayString stringByAppendingString:[[orders objectAtIndex: orderIndex] objectForKey: @"orderdate"]];
    cell.textLabel.text = displayString;
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    return cell;    
}
 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic
    NSLog(@"Calling didSelectRowAtIndexPath");
    int orderIndex = [indexPath indexAtPosition: [indexPath length] - 1];
    NSString *orderLink = [[orders objectAtIndex: orderIndex] objectForKey: @"link"];
    // clean up the link - get rid of spaces, returns, and tabs...
    orderLink = [orderLink stringByReplacingOccurrencesOfString:@" " withString:@""];
    orderLink = [orderLink stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    orderLink = [orderLink stringByReplacingOccurrencesOfString:@"    " withString:@""];
 
    NSLog(@"link: %@", orderLink);
    // open in Safari
    //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:orderLink]];
    [appDelegate getOrderDetails:[[tableView cellForRowAtIndexPath:indexPath] text]];
}
 
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/
 
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
 
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
 
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
 
    if ([orders    count] == 0) {
        NSString * path = @"http://localhost/~santy/feed.xml";
        [self parseXMLFileAtURL:path];
    }
    cellSize = CGSizeMake([ordersTable bounds].size.width, 60);
}
 
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
 
/*
 * Begin of XML Parser methods.
 */
- (void)parserDidStartDocument:(NSXMLParser *)parser{    
    NSLog(@"found file and started parsing");    
}
 
- (void)parseXMLFileAtURL:(NSString *)URL
{    
    orders = [[NSMutableArray alloc] init];
 
    //you must then convert the path to a proper NSURL or it won't work
    NSURL *xmlURL = [NSURL URLWithString:URL];
 
    rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
 
    // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
    [rssParser setDelegate:self];
 
    // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
    [rssParser setShouldProcessNamespaces:NO];
    [rssParser setShouldReportNamespacePrefixes:NO];
    [rssParser setShouldResolveExternalEntities:NO];
 
    [rssParser parse];
}
 
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
 
    NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]];
    NSLog(@"error parsing XML: %@", errorString);
    UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
}
 
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{            
    //NSLog(@"found this element: %@", elementName);
    currentElement = [elementName copy];
    if ([elementName isEqualToString:@"lineitem"]) {
        // clear out our story item caches...
        item = [[NSMutableDictionary alloc] init];
        orderNumber = [[NSMutableString alloc] init];
        orderDate = [[NSMutableString alloc] init];
        materialDescription = [[NSMutableString alloc] init];
        link = [[NSMutableString alloc] init];
    }
 
}
 
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{     
    //NSLog(@"ended element: %@", elementName);
    if ([elementName isEqualToString:@"lineitem"]) {
        // save values to an item, then store that item into the array...
        [item setObject:orderNumber forKey:@"ordernumber"];
        [item setObject:link forKey:@"link"];
        [item setObject:materialDescription forKey:@"materialdescription"];
        [item setObject:orderDate forKey:@"orderdate"];
 
        [orders addObject:[item copy]];
        NSLog(@"adding order: %@", orderNumber);
    }
}
 
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    //NSLog(@"found characters: %@", string);
    // save the characters for the current item...
    if ([currentElement isEqualToString:@"ordernumber"]) {
        [orderNumber appendString:string];
    } else if ([currentElement isEqualToString:@"link"]) {
        [link appendString:string];
    } else if ([currentElement isEqualToString:@"materialdescription"]) {
        [materialDescription appendString:string];
    } else if ([currentElement isEqualToString:@"orderdate"]) {
        [orderDate appendString:string];
    }
 
}
 
- (void)parserDidEndDocument:(NSXMLParser *)parser {
 
    [activityIndicator stopAnimating];
    [activityIndicator removeFromSuperview];
    NSLog(@"all done!");
    NSLog(@"orders array has %d items", [orders count]);
    [ordersTable reloadData];
}
 
- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
 
    // Release any cached data, images, etc that aren't in use.
}
 
- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
 
- (void)dealloc {
    [super dealloc];
}
 
@end
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License