解析具有相同名称的元素?

时间:2011-12-19 14:50:38

标签: iphone objective-c ios ipad nsxmlparser

我使用NSXMLParser,但我有一些它们具有相同名称的元素。所以我想知道我怎么能以不同的方式解析它们呢?

<hours type="array">
    <hour>
        <name>Lun - Dim</name>
        <value>19:00 - 01:00</value>
    </hour>
</hours>
<categories type="array">
    <category>
        <name>Cuisine indienne</name>
        <value>indian</value> 
    </category>
</categories>

1 个答案:

答案 0 :(得分:2)

这是一个粗略的例子:

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



    if ([elementName isEqualToString:@"hours"]) {
           //Tells us we are in hours group
           _isInHoursGroup = YES; 
           //Get our hour object ready
           _myHourObject = [MyHourObject alloc] init];
           return;
      }

    if ([elementName isEqualToString:@"categories"]) {
           _isInCategoriesGroup = YES; 
           _myCategoryObject = [MyCategoryObject alloc] init];
           return;    

    }


}

然后:

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




    if ([elementName isEqualToString:@"hours"]) {
           _isInHoursGroup = NO; 
           return;
    }

    if ([elementName isEqualToString:@"categories"]) {
           _isInCategoriesGroup = NO; 
           return;   
    }

   if (_isInHoursGroup && [didEndElement isEqualToString:@"name"]) {

           //Assumes you have _currentValue variable with the current value in it.
           _myHourObject.myPropert = _currentValue;
           return;
   }

   if (_isInCategoriesGroup && [didEndElement isEqualToString:@"name"]) {

           //Assumes you have _currentValue variable with the current value in it.
           _myCategoryObject.myPropert = _currentValue;
           return;
   }



}