When I try to put your code into a function passing in a string variable I get an error:
The argument 1 of the xml data type method "query" must be a string literal.
That seems to suggest it won't work in a function since it has to be a static string not a dynamic variable.
I like the idea though. Thanks for the post.
Ben