Thanks a lot! I've tested a few cases, and as far as
I can tell your function works perfectly with Saxon.
In eXist, however, it doesn't seem to work. If I use for example
the only output is an empty '<TEI/>' element. If I put '/TEI/text'
as the third parameter, it returns '<text/>'. No doubt, this is
due to some eXist idiosyncracy. Anyone knoes why and what to do
about it? (I'll post a question to the eXist list as well.)