Saurabh Bisht Saurabh Bisht - 4 months ago 20
iOS Question

NSXMLParser ios - How to parse child nodes

I have an xml format, here's the part of it..

<a:IngredientItemIds xmlns:b="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
enter<b:int>206932</b:int><b:int>206930</b:int></a:IngredientItemIds><a:IsGiftCard>false</a:IsGiftCard>


..and so on..

My problem is that the XML parser fetches "none" for element "IngredientItemIds"
Instead what I wanted was an array of all "int" tags..

I am using the methods of NSXML parser foundcharacters, didstartElement and didEndElement

Does Any one know how to parse the child nodes in NSXMLparser ?

Thanks.

Answer

Try this:

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

        // If the current element name is equal to "a:IngredientItemId " then initialize the temporary dictionary.

        if ([elementName isEqualToString:@"a:IngredientItemIds"]) {
            self.dictTempDataStorage = [[NSMutableDictionary alloc]init];
        }

        // Keep the current element.
        self.currentElement = elementName;
    }

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

        if ([elementName isEqualToString:@"a:IngredientItemIds"]) {
           [self.arrNeighboursData addObject:[[NSDictionary alloc] initWithDictionary:self.dictTempDataStorage]];
        }
        else if ([elementName isEqualToString:@"b:int"]){
            // If the b:int element was found then store it.
            [self.dictTempDataStorage setObject:[NSString stringWithString:self.foundValue] forKey:@"b:int"];
        }

        // Clear the mutable string.
        [self.foundValue setString:@""];
    }


    -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
        // Store the found characters if only we're interested in the current element.
        if ([self.currentElement isEqualToString:@"b:int"] ) {

            if (![string isEqualToString:@"\n"]) {
                [self.foundValue appendString:string];
            }
        }
    }