As you want to replace an element, you should simply use the replace
construct, instead of inserting the new element and deleting the old one. Seems much simpler to me:
copy $i := $a
modify (
for $x in $i/descendant-or-self::*[exists(*)]/text()
return replace node $x with <childtext>{$x}</childtext>
)
return $i