There's a couple of good ideas on how to write a function to get an xpath here: http://stackoverflow.com/questions/3454526/how-to-calculate-the-xpath-position-of-an-element-using-javascript

I think something based on those would be a lot cleaner/shorter. It should also be a self-contained function, not a string. executeScript() will convert to string.