Parsing XML: identify / get data for specific element?
I have the following methods in my simple Custom Parser Class, when I execute CALLED: on my data I get ...
Found: OK
Found: 046 3433 5674 3422 4456 8990 1200 5284
My question is how would I go about adding to this so that I can specifically pick out the information for the data element (see below), is there anything I can add to the - 开发者_如何学Python(void)parser: method, how might I do that?
<data version="1.0">2046 3433 5674 3422 4456 8990 1200 5284</data>
Here are sections of my code:
// CLASS:
@interface CustomParser : NSObject <NSXMLParserDelegate> {
}
-(void)parseFile:(NSString *)pathToFile;
@end
@implementation CustomParser
-(void)parseFile:(NSString *)pathToFile {
NSLog(@"parseXMLFile ... \"%@\"", pathToFile);
NSURL *url = [NSURL fileURLWithPath:pathToFile];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser parse];
[parser release];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
NSLog(@"Found: %@", string);
}
@end
.
//CALLED:
CustomParser *newParser = [[CustomParser alloc] init];
[newParser parseFile:fileOnDisk];
... more
[newParser release];
.
//DATA:
<!DOCTYPE tubinerotationdata>
<turbine version="1.0">
<status version="1.0" result="200">OK</status>
<data version="1.0">
2046 3433 5674 3422 4456 8990 1200 5284
</data>
</turbine>
gary
You need to implement the didStartElement and didEndElement methods and use ivars to keep track of the current element name and value.
Example of one way to do it:
//Instance variables:
NSString *currentElementValue;
NSString *statusValue;
NSString *dataValue;
In didStartElement:
currentElementValue = @"";
In foundCharacters:
currentElementValue = [currentElementValue stringByAppendingString:string];
in didEndElement:
if ([elementName isEqualToString:@"status"])
{
statusValue = currentElementValue;
}
else
if ([elementName isEqualToString:@"data"])
{
dataValue = currentElementValue;
}
Alternatively, you could have a ivar that keeps track of the current element name and in foundCharacters set the statusValue and dataValue based on that.
精彩评论