Parsing XML file with NSXMLParser - getting values

前端 未结 4 959
既然无缘
既然无缘 2020-12-08 17:18

I\'ve got a XML file which contains some data I would like to use:






        
相关标签:
4条回答
  • 2020-12-08 18:08

    First you need to create an object that does the parsing. It will instatiate the NSXMLParser instance, set itself as the delegate for the parser and then call the parse message. It can also be responsible for storing your four result arrays:

    NSXMLParser * parser = [[NSXMLParser alloc] initWithData:_data];
    [parser setDelegate:self];
    BOOL result = [parser parse];
    

    The message you are most interested in implementing in your delegate objects is didStartElement. This guy gets called for each element in your XML file. In this callback you can add your name, price & where attributes to their respective arrays.

    - (void)parser:(NSXMLParser *)parser
    didStartElement:(NSString *)elementName
      namespaceURI:(NSString *)namespaceURI
     qualifiedName:(NSString *)qualifiedName
        attributes:(NSDictionary *)attributeDict
    {
        // just do this for item elements
        if(![elementName isEqual:@"item"])
            return;
    
        // then you just need to grab each of your attributes
        NSString * name = [attributeDict objectForKey:@"name"];
    
        // ... get the other attributes
    
        // when we have our various attributes, you can add them to your arrays
        [m_NameArray addObject:name];
    
        // ... same for the other arrays
    }
    
    0 讨论(0)
  • 2020-12-08 18:11

    To get the value between the tags (e.g. "This is the first product.") you can override - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

    0 讨论(0)
  • 2020-12-08 18:12

    you have to consider the dictionary of item tag as an array and three tag (name,price and where)as the object at index 0,1,2

    0 讨论(0)
  • 2020-12-08 18:13

    in the follwing method

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    
        if([elementName isEqualToString:@"item"]) {
    
            NSString *name=[attributeDict objectForKey:@"name"];
            NSString *price=[attributeDict objectForKey:@"price"];
            NSString *where=[attributeDict objectForKey:@"where"];
        }
    }
    
    0 讨论(0)
提交回复
热议问题