iphone xml parser

本文介绍了一个使用Objective-C编写的iOS应用程序,该程序通过解析XML文件来动态填充一个应用列表,并展示了如何实现XML解析器代理方法以提取所需的应用信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



#import <UIKit/UIKit.h>


@interface MoreAppViewController : UITableViewController {
UIActivityIndicatorView * activityIndicator;

NSXMLParser *xmlParser;
NSMutableArray *appList;
NSMutableDictionary *item;

NSString *currentElement;
NSMutableString *name, *description, *picurl, *url;
}

-(id)init;

-(void) parseXMLFileAtURL:(NSString*)URL;

@end



#import "MoreAppViewController.h"


@implementation MoreAppViewController

-(id)init{
self = [super init];
if(self!=nil){
self.title = @"More";
}
return self;
}
/*
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (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 {
[super loadView];
if ([appList count] == 0) {

/*
// make the activity indicator as the right side button
CGRect frame = CGRectMake(0.0, 0.0, 25.0, 25.0);
activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:frame];
[activityIndicator startAnimating];
[activityIndicator sizeToFit];
activityIndicator.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleTopMargin |
UIViewAutoresizingFlexibleBottomMargin);

UIBarButtonItem *loadingView = [[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
loadingView.target = self;
self.navigationItem.rightBarButtonItem = loadingView;
*/
NSString * path = @"http://www.host.net/info/info.xml";
[self parseXMLFileAtURL:path];
}

}


-(void) parseXMLFileAtURL:(NSString*)URL{
appList = [[NSMutableArray alloc]init];
//you must then convert the path to a proper NSURL or it won't work
NSURL *xmlURL = [NSURL URLWithString:URL];

// here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
// this may be necessary only for the toolchain
xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];

// Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
[xmlParser setDelegate:self];

// Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
[xmlParser setShouldProcessNamespaces:NO];
[xmlParser setShouldReportNamespacePrefixes:NO];
[xmlParser setShouldResolveExternalEntities:NO];

[xmlParser parse];
}

- (void)parserDidStartDocument:(NSXMLParser *)parser {
NSLog(@"found file and started parsing");
}

- (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:@"app"]) {
// clear out our story item caches...
item = [[NSMutableDictionary alloc] init];
name = [[NSMutableString alloc] init];
description = [[NSMutableString alloc] init];
picurl = [[NSMutableString alloc] init];
url = [[NSMutableString alloc] init];
}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{

//NSLog(@"ended element: %@", elementName);
if ([elementName isEqualToString:@"app"]) {
// save values to an item, then store that item into the array...
[item setObject:name forKey:@"name"];
[item setObject:description forKey:@"description"];
[item setObject:picurl forKey:@"picurl"];
[item setObject:url forKey:@"url"];

[appList addObject:[item copy]];
NSLog(@"adding story: %@", name);
}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//NSLog(@"found characters: %@", string);
// save the characters for the current item...
if ([currentElement isEqualToString:@"name"]) {
[name appendString:string];
} else if ([currentElement isEqualToString:@"description"]) {
[description appendString:string];
} else if ([currentElement isEqualToString:@"picurl"]) {
[picurl appendString:string];
} else if ([currentElement isEqualToString:@"url"]) {
[url appendString:string];
}
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {

[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];

NSLog(@"all done!");
NSLog(@"stories array has %d items", [appList count]);
//[newsTable reloadData];
[self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [appList count];
}

- (UITableViewCell *)tableView:(UITableView *)mtableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"app-flist-cell";
UITableViewCell *cell = (UITableViewCell*)[mtableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell){
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]autorelease];
}
NSUInteger row = [indexPath row];
NSDictionary *caiDictionary = [appList objectAtIndex:row];
cell.textLabel.text = [caiDictionary objectForKey:@"name"];
cell.detailTextLabel.text = [caiDictionary objectForKey:@"description"];
NSString *iconurl = [caiDictionary objectForKey:@"picurl"];
//if([picurl1 isEqualToString:@""]){

////}
NSLog(@"%@",iconurl);
NSURL *iconurl_1 = [NSURL URLWithString:iconurl];
NSData *data = [NSData dataWithContentsOfURL:iconurl_1];
UIImage *img = [[UIImage alloc]initWithData:data];
cell.imageView.image = [UIImage imageNamed:@"icon.png"];
//cell.imageView.image = img;
[img release];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"#######");
NSUInteger row = [indexPath row];
NSDictionary *dictionary = [appList objectAtIndex:row];
NSString *appurl = [dictionary objectForKey:@"url"];
NSLog(@"##%@",appurl);
//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url1]];
//NSString *thePhone = [NSString stringWithFormat:@"tel:%@",theNumber];
//NSURL *url = [[NSURL alloc] initWithString:thePhone];
NSURL *ccj = [NSURL URLWithString:appurl];
BOOL a = [[UIApplication sharedApplication] openURL:ccj];
if(a){
NSLog(@"00");
}else{
NSLog(@"001");
}

//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://123456"]];
}


/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (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



NSString *url = [[NSString alloc] initWithFormat:@"http://www.example.com.pt/iPhone/resize.php?max_height=80&max_width=58&qt=80&imgpath=%@",[aNoticia.img substringFromIndex:3]];
cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[ NSURL URLWithString:url]]];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值