Basically I want to write a class for parsing XML document for my iphone apps.
Here is my header file for the parser which parses a news feed
@interface NewsXML : NSObject<NSXMLParserDelegate>
{
@private
NSXMLParser *xmlParser;
NSString *currentElement;
NSMutableString *currentTitle;
NSMutableString *currentDate;
NSMutableString *currentDetail;
NSMutableString *currentImageURL;
NSMutableString *currentThumbnailURL;
NSMutableString *currentAlt;
}
@property (nonatomic, assign) NSObject<NewsXMLDelegate> *delegate;
@property (nonatomic, strong) NSMutableArray *newsItems;
@property (nonatomic, strong) NSURL *url;
- (void)fetch;
@end
There is an array ‘newsItems” which holds the fetched objects from the XML after the method ‘fetch’ is called.
However there are several types of XML files in my program I would like to parse. Each type of XML file have different fields. (Eg : title, date, detail etc)
I create different class (E.g. NewsItem , FooItem , AbcItem ) for holding the Items from different XML files.
I still cannot figure out how to make this XML Parser class to be more general so that the NSMutableArray of items can hold different type of items (NewsItem, FooItem ..) for each case. Now I need to write different XML parser class for each xml file.
So how can this be done in a more general way?
EDIT
Sorry for being unclear.. When the parser parse each item, it will create a new object like ‘NewsItem’, ‘FooItem’ for holding the data and then add it to the array. However, the parser class should not know the existence of these classes (Since more and more item class will be added later). Then how this xml parser class can create the proper objects and add them to the array properly? Is there any way to initialize the parser class with the class of the item?
After reading your comment, I don’t think that what you have in mind is a good design for the classes. I think that the XML parser should simply parse XML in a standard way and always return the same thing, and your classes (such as NewsItem, FooItem, etc) should know how to create themselves with the parsed XML. This is much more robust.
I do this in several apps I’ve made. My NewsItem or FooItem classes implement a function that looks like this:
This way the XML parsed data is always the same (you dont change the XML parser) and if you need the class to handle the data differently, you change the class’ own
initWithXMLDatafunction, instead of changing the XML parser. The XML parser never needs to know about the existence of any other classes.