Shawn Sharp
Shawn Sharp

Reputation: 471

count elements in xml using objective c

I've got an XML file and I need to count how many times the element appears in it using Objective-C. How should I do this?

   <?xml version="1.0" encoding="ISO-8859-1"?>

<residents>
    <resident id="1">
        <name>
            <first>David</first>
            <last>Dollar</last>
        </name>
    </resident>

    <resident id="2">
        <name>
            <first>Michael</first>
            <last>Nipp</last>
        </name>
    </resident>

etc...

Upvotes: 1

Views: 476

Answers (1)

Chris Livdahl
Chris Livdahl

Reputation: 4740

I would set your class as the delegate of the parser, then this class will receive parse events such as parser:didStartElement:, parser:foundCharacters: and parser:didEndElement:.

self.parser = [[NSXMLParser alloc] initWithData:xmlData];
[self.parser setDelegate:self]; 
[self.parser parse]; 

I would create a count variable in your parser delegate. Anytime an element is found, the didStartElement: function is called on the parser delegate. Check if it's the "resident" element and increment the count if so.

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

    if ([elementName isEqualToString:@"resident"]) {

        self.count += 1; 

    }
}

Upvotes: 1

Related Questions