XQuery is like a breath of fresh air!
I've been processing a lot of XML in Cocoa recently and thought to myself there must be a better way to do this. Rather then loop through the elements pulling out the information I need. That's when I remembered about XPath. Looking in the Apple docs I stumbled upon XQuery which seems to allow a more fine grained control over how you process the XML
I'm processing XML from svn commands like:
svn --xml --verbose stat .which gets the status of all files below the
current directory and can return hundreds if not thousands of entries as you can imagine. Here is a snippet.
<status>
<target path=".">
<entry path="build">
<wc-status props="none" item="unversioned">
</wc-status>
</entry>
<entry path="stat.xml">
<wc-status props="none" item="unversioned">
</wc-status>
</entry>
... blah blah
</status>
Now I want to get all the files that are unversioned or modified. This information is stored in each entry nodes wc-status node item parameter. So I run this XQuery over the XML which returns the nodes I care about:
for $p in .//entry let $filter := "modified unversioned" where contains($filter, $p/wc-status/@item) return $p
line 1 filters the XML so I am only looking at entry nodes.
line 2 sets up a string containing the two strings I will be looking for
line 3 filters in nodes (entry nodes) where the item attribute value is contained in the $filter string.
line 4 returns all elements that made it past all the tests.
The Cocoa class NSXMLNode has a method:
-(NSArray *)objectsForXQuery:(NSString *)xquery
constants:(NSDictionary *)constants
error:(NSError **)error
which as you can see returns an array of all the elements that match the XQuery given. It's really cool! Here are the Cocoa docs for the XML Classes.
If you want to see what an XQuery returns with some sample XML then look in /Developer/Examples/Foundation/XMLBrowser. It's a piece of example code thats comes free with the Apple Developer Tools to show CoreData but it's a nice little tool for testing XQueries.