I recently added a very nice feature to one of my Open Source projects, TBXMLEx, which is the possibility of directly access any node without having to loop through all its parent nodes. This is very useful when you know beforehand where the node is located at. The sintax is very clean and concise. Suppose you have the following XML:
NSString *xml = @"<data> \ <a> \ <a1/> \ <a1/> \ <a1/> \ </a> \ \ <b/> \ <b/> \ <c/> \ \ <d> \ <d1> \ <d11/> \ <d21/> \ </d1> \ \ <d2> \ <d21/> \ <d22> \ <d221/> \ </d22> \ </d2> \ </d> \ </data>";
and that you need to access the “d221″ node, which is pretty deed inside the structure. Using TBXMLEx it is straightforward do to so:
TBXMLEx *parser = [TBXMLEx parserWithXML:xml]; NSArray *result = [parser.rootElement query:@"/d/d2/d22/d221"]; TBXMLElementEx *element = [result objectAtIndex:0];
The key point in the previous code sample is the “query” method (a member of TBXMLElementEx), which takes a path as argument and returns all nodes that matches the criteria, as TBXMLElementEx instances. Right now it supports only simple expressions, but nevertheless it’s a quite useful feature .
You may wonder why not use XPath instead. The point is, while very powerful, you’ll need extra libraries to work with XPath, and it can take some time to master its syntax. The “query” method I implemented does not intend to take over XPath nor reimplement its features, it is just a convenient, syntax sugar method to do regular tasks we face on a daily basis, and while someday it may be improved to be more powerful, XPath will always be the choice when you need to do nasty thigns with XML.
TBXMLEx is an Open Source library freely available at https://github.com/rafaelsteil/tbxmlex