I just love it when you need something simple and easy that perfectly suits your needs. I needed some lightweight XML parser for iOS, and I found it.
To be honest (since I’m coming from java background), I didn’t quite fall in love with objective-c at first, and it seemed to be that I needed a lot more code to make some basic stuff work. For example XML parsing. NSXMLParser is ok, but it’s event driven (link #1, link #2). I wanted some dead simple DOM parser.
So the whole library is just two classes SMXMLElement and SMXMLDocument. To show you how simple it is to parse a file, here is a (reduced) snippet from my application:
- (void) parseData:(NSData *) { NSError *error; SMXMLDocument *document = [SMXMLDocument documentWithData:data error:&error]; // check for errors if (error) { DDLogError(@"Error while parsing the document: %@", error); return nil; } // Array of objects that we are returning NSMutableArray *result = [[NSMutableArray alloc] init]; // Get the videos node SMXMLElement *videos = document.root; // Go through every sub-element "video" for (SMXMLElement *video in [videos childrenNamed:@"video"]) { VideoInfo *info = [[VideoInfo alloc] init]; info.name = ; // Get other values from XML... [result addObject:info]; [info release]; } return result; }
A shorter version of XML that the code above parses is:
<videos> <video> <name>Yup, this a name of a video</name> </video> <video> <name>And another one :)</name> </video> </videos>
As you can see I’m only using (NSString*) valueWithPath:(NSString *) here, but there are a couple more
- (SMXMLElement *)childNamed:(NSString *)name; - (NSArray *)childrenNamed:(NSString *)name; - (SMXMLElement *)childWithAttribute:(NSString *)attributeName value:(NSString *)attributeValue; - (NSString *)attributeNamed:(NSString *)name; - (SMXMLElement *)descendantWithPath:(NSString *)path; - (NSString *)valueWithPath:(NSString *)path;
Do you really need anything else (in some small applications)? :)
Really awesome, kudos to the creators.
I am really in need of this code, is it possible to send me the whole code, if you don’t mind?
Hi,
If you want another method to parse XML. There is a spanish tutorial to do that task:
http://www.apprendemos.com/tutoriales/ios/parser-xml-recorrer-iphone
I hope it help you
Hi! It looks easy! Is it possible to send me the whole code too? I’m c-programmer, but I’m learning ios now… Thanks a lot!
Good Job Man!!! Helps a lot!!! Code available in https://github.com/nfarina/xmldocument/releases