1. to_xmlstr can be replaced with calls to xmlCharStrdup. 2. don't need xml_xmlnodetostr either -- just use xml_xmlnodetoxmltype (which returns text*) and extract the cstring from the varlena. It's a bit more wasteful in terms of cycles, but I don't think we care. If we do care, change the function so that it returns cstring, and have the callers that want text wrap it in cstring_to_text. 3. have a new perValueCxt memcxt in TableExprState, child of buildercxt, and switch to it just before GetValue() (reset it just before switching). Then, don't worry about leaks in GetValue. This way, the text* conversions et al don't matter.
After that I think we're going to need to get this working on top of Andres' changes. Which I'm afraid is going to be rather major surgery, but I haven't looked.
I'll try to clean xml part first, and then I can reflect the SRF changes. I am not sure if I understand to all your proposed changes here, I have to look there.