0

基本上,我的 tableview 填充了街道名称列表,该列表是从 XML 解析的数据,街道按字母顺序排序。

XML 有多个用于 A、B、C 等的街道。(基本上超过 1 个,每个大小不同)

问题是:基本上它将整个数组添加到 A 节、B 节等。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView)
{
    return [self.filteredListContent count];
}
else
{
    return [xmlDataArray count];
}  
}

我需要一种方法将 XML 分解为多个数组,以将 A、B、C 等中包含的街道填充到正确的部分中。

我已阅读有关创建字典和创建键的多篇文章,但我不知道如何从解析的 XML 中执行此操作。一旦我在字典中有它,我如何填充 tableView?我有一个单独的 indexTitles 数组,AZ 索引显示在右侧。但是这当然行不通,因为数据需要根据 AZ 分类到自己的部分中。

非常感谢任何帮助或建议。

非常感谢!

4

1 回答 1

0

有很多很好的教程来学习如何正确解析 XML,这里有一个快速的:

在.h

@interface ObjectName : ObjectSuperclass <NSXMLParserDelegate> {
    NSMutableString *currentElement;
    NSMutableString *childElement;
    NSMutableDictionary *dictionary;
}

@end

在 .m 中,插入这些 NSXMLParser 委托方法:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{    
  currentElement = nil;
  currentElement = [elementName copy];
  if ([elementName isEqualToString:@"xmlParentElement"]) {
    //This means the parser has entered the XML parent element named: xmlParentElement
    //All of the child elements that need to be stored in the dictionary should have their own IVARs and declarations.
    childElement = [[NSMutableString alloc] init];
  }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
  //For all child elements, run this if statement.
  if (currentElement isEqualToString:@"childElement") {
    [childElement appendString:string];
  }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{   
  if ([elementName isEqualToString:@"parentElement"]) {
    [dictionary addObject:childElement forKey:@"childElement"];
    //And devise a system for indexing (this could be converting the address string in to an array and taking objectAtIndex:0.. any way you choose, add that object below:
    [dictionary addObject:@"A" forKey@"index"];
  }
}  

现在已经完成了,使用常规的 UITableViewController 委托方法来创建表,此外,使用这些委托方法来创建侧索引:

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
  return [dictionary objectForKey:@"index"];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
  return index;
}
于 2012-06-14T18:45:29.990 回答