I don't know why you're calling an extension function to do something that can be done very easily in XSLT. Extension functions are implementation-defined, but I would expect most implementations to require them to return XPath values - strings or nodes - not a chunk of serialized XML (or HTML). Remember that XSLT is about transforming trees, not lexical XML.
Rewrite your code in XSLT, it will be much cleaner.
Michael Kay
http://www.saxonica.com/
Author, XSLT Programmer's Reference and XPath 2.0 Programmer's Reference