Not to take anything away from what joe put together for you I bet if you put Eirikur's solution into an inline table valued function it would perform much better than any scalar UDF that produces the same XML.
Note this article:
How to Make Scalar UDFs Run Faster (SQL Spackle)[/url]
-- Itzik Ben-Gan 2001