iPhone XML 解析问题

发布于 2024-11-25 23:29:50 字数 980 浏览 0 评论 0原文

我是 iPhone 开发新手,我正在尝试解析此链接并将其放在我的表格视图上,但是当我的表格视图显示时,标题不会显示在行中。我在这里做错了什么?

- (void)viewDidLoad {
[super viewDidLoad];

self.title = @"RSS Feeds";

rssList = [[NSMutableArray alloc] initWithCapacity:1];

NSString *URLString = [[NSString alloc]initWithFormat:@"http://www.rpg.net/index.xml"];
NSLog(@"%@",URLString);



NSURL *xmlURL = [NSURL URLWithString:URLString];


NSXMLParser *firstParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[firstParser setDelegate:self];
[firstParser parse];

[URLString release];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {

if ([elementName compare:@"item"] == NSOrderedSame) {

[rssList addObject:[[NSDictionary alloc] initWithObjectsAndKeys:
[attributeDict objectForKey:@"title"],@"title",
[attributeDict objectForKey:@"link"],@"link",
nil]];

}
}

I am new to iPhone dev and I am trying to parse this link and put it on my tableview, however when my tableview shows up, the titles do not show up in the rows. What I am doing wrong here?

- (void)viewDidLoad {
[super viewDidLoad];

self.title = @"RSS Feeds";

rssList = [[NSMutableArray alloc] initWithCapacity:1];

NSString *URLString = [[NSString alloc]initWithFormat:@"http://www.rpg.net/index.xml"];
NSLog(@"%@",URLString);



NSURL *xmlURL = [NSURL URLWithString:URLString];


NSXMLParser *firstParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[firstParser setDelegate:self];
[firstParser parse];

[URLString release];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {

if ([elementName compare:@"item"] == NSOrderedSame) {

[rssList addObject:[[NSDictionary alloc] initWithObjectsAndKeys:
[attributeDict objectForKey:@"title"],@"title",
[attributeDict objectForKey:@"link"],@"link",
nil]];

}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

卖梦商人 2024-12-02 23:29:50

使用它从 rss feed 进行 xml 解析。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}


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


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *MyIdentifier = @"MyIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}

// Set up the cell
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
[cell setText:[[stories objectAtIndex: storyIndex] objectForKey: @"title"]];

return cell;
}


 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 // Navigation logic

 int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];

 NSString * storyLink = [[stories objectAtIndex: storyIndex] objectForKey: @"link"];

 // clean up the link - get rid of spaces, returns, and tabs...
 storyLink = [storyLink stringByReplacingOccurrencesOfString:@" " withString:@""];
 storyLink = [storyLink stringByReplacingOccurrencesOfString:@"\n" withString:@""];
 storyLink = [storyLink stringByReplacingOccurrencesOfString:@" " withString:@""];

 NSLog(@"link: %@", storyLink);
 // open in Safari
 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];
  }


  - (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
  }

  - (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];

if ([stories count] == 0) {
    NSString * path = @"http://feeds.feedburner.com/TheAppleBlog";
    [self parseXMLFileAtURL:path];
}

cellSize = CGSizeMake([newsTable bounds].size.width, 60);
    }

    - (void)viewWillDisappear:(BOOL)animated {
     }

   - (void)viewDidDisappear:(BOOL)animated {
   }




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

   }

   - (void)parseXMLFileAtURL:(NSString *)URL
     {  
stories = [[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
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:@"item"]) {
    // clear out our story item caches...
    item = [[NSMutableDictionary alloc] init];
    currentTitle = [[NSMutableString alloc] init];
    currentDate = [[NSMutableString alloc] init];
    currentSummary = [[NSMutableString alloc] init];
    currentLink = [[NSMutableString alloc] init];
}

     }

   - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{     
//NSLog(@"ended element: %@", elementName);
if ([elementName isEqualToString:@"item"]) {
    // save values to an item, then store that item into the array...
    [item setObject:currentTitle forKey:@"title"];
    [item setObject:currentLink forKey:@"link"];
    [item setObject:currentSummary forKey:@"summary"];
    [item setObject:currentDate forKey:@"date"];

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

    }

   - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//NSLog(@"found characters: %@", string);
// save the characters for the current item...
if ([currentElement isEqualToString:@"title"]) {
    [currentTitle appendString:string];
} else if ([currentElement isEqualToString:@"link"]) {
    [currentLink appendString:string];
} else if ([currentElement isEqualToString:@"description"]) {
    [currentSummary appendString:string];
} else if ([currentElement isEqualToString:@"pubDate"]) {
    [currentDate appendString:string];
}

     }

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

[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];

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





  - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
    }


    - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
     }


   - (void)dealloc {

[currentElement release];
[rssParser release];
[stories release];
[item release];
[currentTitle release];
[currentDate release];
[currentSummary release];
[currentLink release];

[super dealloc];
     }

use this for xml parsing from a rss feed.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}


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


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *MyIdentifier = @"MyIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}

// Set up the cell
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
[cell setText:[[stories objectAtIndex: storyIndex] objectForKey: @"title"]];

return cell;
}


 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 // Navigation logic

 int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];

 NSString * storyLink = [[stories objectAtIndex: storyIndex] objectForKey: @"link"];

 // clean up the link - get rid of spaces, returns, and tabs...
 storyLink = [storyLink stringByReplacingOccurrencesOfString:@" " withString:@""];
 storyLink = [storyLink stringByReplacingOccurrencesOfString:@"\n" withString:@""];
 storyLink = [storyLink stringByReplacingOccurrencesOfString:@" " withString:@""];

 NSLog(@"link: %@", storyLink);
 // open in Safari
 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];
  }


  - (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
  }

  - (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];

if ([stories count] == 0) {
    NSString * path = @"http://feeds.feedburner.com/TheAppleBlog";
    [self parseXMLFileAtURL:path];
}

cellSize = CGSizeMake([newsTable bounds].size.width, 60);
    }

    - (void)viewWillDisappear:(BOOL)animated {
     }

   - (void)viewDidDisappear:(BOOL)animated {
   }




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

   }

   - (void)parseXMLFileAtURL:(NSString *)URL
     {  
stories = [[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
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:@"item"]) {
    // clear out our story item caches...
    item = [[NSMutableDictionary alloc] init];
    currentTitle = [[NSMutableString alloc] init];
    currentDate = [[NSMutableString alloc] init];
    currentSummary = [[NSMutableString alloc] init];
    currentLink = [[NSMutableString alloc] init];
}

     }

   - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{     
//NSLog(@"ended element: %@", elementName);
if ([elementName isEqualToString:@"item"]) {
    // save values to an item, then store that item into the array...
    [item setObject:currentTitle forKey:@"title"];
    [item setObject:currentLink forKey:@"link"];
    [item setObject:currentSummary forKey:@"summary"];
    [item setObject:currentDate forKey:@"date"];

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

    }

   - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//NSLog(@"found characters: %@", string);
// save the characters for the current item...
if ([currentElement isEqualToString:@"title"]) {
    [currentTitle appendString:string];
} else if ([currentElement isEqualToString:@"link"]) {
    [currentLink appendString:string];
} else if ([currentElement isEqualToString:@"description"]) {
    [currentSummary appendString:string];
} else if ([currentElement isEqualToString:@"pubDate"]) {
    [currentDate appendString:string];
}

     }

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

[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];

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





  - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
    }


    - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
     }


   - (void)dealloc {

[currentElement release];
[rssParser release];
[stories release];
[item release];
[currentTitle release];
[currentDate release];
[currentSummary release];
[currentLink release];

[super dealloc];
     }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文