title: How to convert text inside a node into child node using xquery update?
body: <p>I have a xml document like</p>
  
  <pre><code>&lt;root&gt;
    &lt;first&gt;
      First Level
      &lt;second&gt;
        second level
         &lt;third&gt;
           Third Level
         &lt;/third&gt;
      &lt;/second&gt;
      &lt;second2&gt;
        another second level
      &lt;/second2&gt;
    &lt;/first&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p>How to convert this document with all nodes, that means if a node contains <code>text</code> and <code>child node</code> convert text into a child node (let's say <strong>childtext</strong>) using xquery-update</p>
  
  <pre><code>&lt;root&gt;
    &lt;first&gt;
      &lt;childtext&gt;First Level&lt;/childtext&gt;
      &lt;second&gt;
        &lt;childtext&gt;second level&lt;/childtext&gt;
         &lt;third&gt;
           Third Level
         &lt;/third&gt; 
      &lt;/second&gt;
      &lt;second2&gt;
        another second level
      &lt;/second2&gt;
    &lt;/first&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p>And here is what I tried:</p>
  
  <pre><code>let $a :=
  &lt;root&gt;
    &lt;first&gt;
      First Level
      &lt;second&gt;
        second level
         &lt;third&gt;
           Third Level
         &lt;/third&gt;
      &lt;/second&gt;
      &lt;second2&gt;
        another second level
      &lt;/second2&gt;
    &lt;/first&gt;
  &lt;/root&gt;
  return 
  copy $i := $a
  modify (
    for $x in $i/descendant-or-self::*
    return (
      if($x/text() and exists($x/*)) then (
        insert node &lt;childtext&gt;
          {$x/text()}
         &lt;/childtext&gt; as first into $x
          (: here should be some code to delete the text only:)
      ) else ()
    )
  )
  return $i
  </code></pre>
  
  <p>I could not delete the text which has sibling node.</p>