I know nothing about XPath, so take it for what it's worth, but this method of searching seems a bit backwards. That'd be like giving your OS of choice a file called /path/to/file, having the OS look for all files called 'file', anf for each one, seeing if it's in a directory called 'to', etc. If you have a heirarchical structure, best to make use of that fact and narrow your search quickly. A nested hash structure comes to mind for implementation...this way, you can see if