How can I parse an XML file in Objective C
ios, objective-c
Solution
You couldnt get the firstname,lastname,etc in your attributeDict. Attribute dictionary holds values like in the below format
<count n="1">
In the above example attributeDict holds the value for n
In order to parse the given xml, you can use the below code.
Declare the objects
Politician *politician;
NSString *curElement;
NSMutableArray *politicians;
BOOL isCongressNumbers;
Initialize the politicians in viewDidLoad
politicians = [[NSMutableArray alloc]init];
Add the delegate methods
#pragma mark - NSXMLParser Delegate
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"item"]) {
politician = [[Politician alloc]init];
} else if ([elementName isEqualToString:@"congress_numbers"]) {
isCongressNumbers = YES;
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
curElement = string;
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"item"] && !isCongressNumbers) {
[politicians addObject:politician];
} else if ([elementName isEqualToString:@"firstname"]) {
politician.name = curElement;
} else if ([elementName isEqualToString:@"lastname"]) {
politician.lName = curElement;
} else if ([elementName isEqualToString:@"birthday"]) {
politician.bDay = curElement;
} else if ([elementName isEqualToString:@"congress_numbers"]) {
isCongressNumbers = NO;
}
}
Problem
I'm trying to parse this xml file. The problem I'm having is that I'd like to use the `-(void)parser:(NSXMLParser*)parser didStartElement` ... to drill down into several levels of this xml file. This is what I have so far: ``` #pragma didStartElement (from the parser protocol) - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { // Choose the tag if ([elementName isEqualToString:@"item"]) { NSString *firstName = [attributeDict valueForKey:@"firstname"]; NSString *lastName = [attributeDict valueForKey:@"lastname"]; NSString *birthDay = [attributeDict valueForKey:@"birthday"]; Politician *politician = [[Politician alloc] initWithName:firstName lName:lastName bDay:birthDay]; if (politician != nil) { [people addObject:politician]; } } } ``` The problem is that this code does not drill down. Is there a way to selectively start the parsing from a specific tag (say: person) and check for the keys of that tag or to rewrite the "elementName's" value so I can use multipe if statements? What's the right way of doing this? Thanks much.