Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSXMLParser example

I have an XML like this

<IS>
    <Value>
        <Signature>-804</Signature>
        <Amount>139</Amount>
    </Value>
    <Value>
        <Signature>-845</Signature>
        <Amount>639466</Amount>
    </Value>
    <Value>
        <Signature>-811</Signature>
        <Amount>16438344</Amount>
    </Value>
    <Value>
        <Signature>-1115</Signature>
        <Amount>-159733</Amount>
    </Value>
</IS>

Now I want to parse only specific values from this. For example, how do I get the value for the node having corresponding signature as -804

Please help me..

I know the basics of NSXMLParser, but do not know how to acheive conditional parsing.

Thank you.

like image 740
copenndthagen Avatar asked Jan 16 '11 13:01

copenndthagen


1 Answers

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    currentKey = nil;
    [currentStringValue release];
    currentStringValue = nil;
    if([elementName isEqualToString:@"Value"]){
        //alloc some object to parse value into
    } else if([elementName isEqualToString:@"Signature"]){
        currentKey = @"Signature";
        return;
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    if(currentKey){
        if(!currentStringValue){
            currentStringValue = [[NSMutableString alloc] initWithCapacity:200];
        }
        [currentStringValue appendString:string];
    }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    if([elementName isEqualToString:@"Signature"] && [currentStringValue intValue] == 804){
        ivar.signature = [currentStringValue intValue];
        return;
    }
}

Something like this. Note I havent really tested this code on compiler so there will be syntax errors here & there.

like image 53
Asad Khan Avatar answered Sep 18 '22 13:09

Asad Khan