If you install libxml2 as the dependency of GNUstep, you can use the built-in XML support of GNUstep, which is GSXML and related classes.
The header of XML support is in GNUstep/System/Library/Headers/GNUstepBase/GSXML.h. If you compile GNUstep as the addition library on MacOS X, you can also use it on Mac.
Here is a very simple example of GSXML. I will read the RSS file, which is a XML format for news, and parse it with GSXML. I will use SAX handler to handle the result of XML parser. Therefore, I need an object as SAX handler.
RSSHandler.h
#include <GNUstepBase/GSXML.h> @interface RSSHandler: GSSAXHandler { BOOL shouldPrint; } @end
RSSHandler.m
#include <Foundation/Foundation.h> #include "RSSHandler.h" @implementation RSSHandler - (void) startElement: (NSString *) elementName attributes: (NSMutableDictionary *) elementAttributes { if ( [elementName isEqualToString: @"title"] || [elementName isEqualToString: @"description"] ) shouldPrint = YES; else shouldPrint = NO; } - (void) characters: (NSString *) name { if (shouldPrint) printf([name cString]); } - (void) endElement: (NSString *) elementName { if ( [elementName isEqualToString: @"title"] || [elementName isEqualToString: @"description"] ) printf("\n"); } @end
Basically, XML parser will call SAX handler for each data type. Here, I only print out the title and description of the news.
Once I have a SAX handler, I can use GSXML to parse the RSS news.
main.m
#include <Foundation/Foundation.h> #include <GNUstepBase/GSXML.h> #include "RSSHandler.h" int main (int argc, const char **argv) { NSAutoreleasePool *pool = [NSAutoreleasePool new]; NSURL *url = [NSURL URLWithString: @"http://rss.news.yahoo.com/rss/topstories"]; RSSHandler *handler = [RSSHandler handler]; GSXMLParser *parser = [GSXMLParser parserWithSAXHandler: handler withContentsOfURL: url]; [parser parse]; RELEASE(pool); return 0; }
That's all. You can change the URL for other RSS news. Just remember that GSXML is under directory GNUstepBase, not in Foundation so that it won't conflict with header of Cocoa if you use it as additional libraries on MacOS X.