views:

73

answers:

1

If I knew how to phrase this I could probably find the answer on Google. I need an XML parser which I can call out to other XML parsers with.

For example:

<car>
    <driver>
        <name />
        <age />
        <height />
    </driver>
    <make>
        <name />
        <nationality />
        <age />
    </make>
    <engine>
        <horsepower />
        <displacement />
        <mileage />
    </engine>
</car>

I need parser which will start parsing Car, get to Driver and give ALL of Driver to a separate parser class, then continue on with make, etc.

If you think of it as a state machine, I need a parser where some states can be different classes.

+4  A: 

If you are using NSXMLParser you can switch the delegate when you find an element:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
  if ([elementName isEqualToString:@"driver"]) {
    parser.delegate = driverDelegate;
    driverDelegate.parentDelegate = self;
    // Maybe call [driverDelegate parser:didStartElement:...]
  }
}

And then change it back when you are done with the other delegate (in driverDeleagate's class):

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
  if ([elementName isEqualToString:@"driver"]) {
    parser.delegate = parentDelegate;
  }
}
Aleph
This is exactly what I was looking to do. Thanks.
Reed Morse