title: Flattening XML with XQuery
body: <p>I am trying to flatten an XML hierarchy to the text nodes where the output tag names are the hyphen concatenated tags on the path of each text node.  I amusing the sample XML provided at <a href="http://www.chilkatsoft.com/xml-samples/bookstore.xml" rel="nofollow noreferrer">http://www.chilkatsoft.com/xml-samples/bookstore.xml</a> as input.</p>
  
  <p>So far I have created this XQuery:</p>
  
  <pre><code>declare function local:flatten($prefix as xs:string*, $nodes as node()*) as node()*
  {
      for $node in $nodes
      return
          typeswitch($node)
              case element() return
                  local:flatten(insert-before($prefix, 1, $node/name()), $node/node())
              case text() return
                  element {string-join(fn:reverse($prefix), '-')} {string($node)}
              default return
                  'oops'      
  }; 
  
  for $b in //bookstore/book return 
      local:flatten((), $b)
  </code></pre>
  
  <p>This mostly works but the output looks like:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;book&gt;
  &lt;/book&gt;
  &lt;book-title&gt;The Iliad and The Odyssey&lt;/book-title&gt;
  &lt;book&gt;
  &lt;/book&gt;
  &lt;book-price&gt;12.95&lt;/book-price&gt;
  &lt;book&gt;
  &lt;/book&gt;
  &lt;book-comments&gt;
  &lt;/book-comments&gt;
  &lt;book-comments-userComment&gt; Best translation I've read. &lt;/book-comments-userComment&gt;
  &lt;book-comments&gt;
  &lt;/book-comments&gt;
  &lt;book-comments-userComment&gt; I like other versions better. &lt;/book-comments-userComment&gt;
  &lt;book-comments&gt;
  &lt;/book-comments&gt;
  &lt;book&gt;
  &lt;/book&gt;
  ...
  </code></pre>
  
  <p>I don't care about the lack of a root element at this time (one step at a time) but I don't want the spurious empty parent tags between the correctly rendered text nodes.  What am I doing wrong?
  I am very new to XQuery and may have made a silly error. </p>