Massive update to the XML selection code

Massive rewrite and clean up of the xml selection code, fixing a few
bugs along the way, probably introducing a lot more along the way :D

THIS COMMIT WILL CONTAIN BUGS - DO NOT UPDATE UNLESS YOU'RE WILLING TO
HELP IN THE FINDING AND REPORTING OF THESE BUGS :)