Rewrite MarkLogic xml document dynamically based on strings in XQuery
<p>I need an XQuery function that is capable of rewriting a document, specifically returning a subset of child nodes, based on an array of strings specifying names of nodes to retrieve. If should satisfy a definition like the below and needs to work with any arbitrary document.</p>

<pre><code>local:apply-node-includes($document, $includedNodeNames as xs:string*)
</code></pre>

<p>Given I had some xml doc</p>

<pre><code>let $doc := 
  &lt;foo a="b"&gt;
    &lt;bar&gt;hello&lt;/bar&gt;
    &lt;baz&gt;1&lt;/baz&gt;
    &lt;bang&gt;
      &lt;text&gt;world&lt;/text&gt;
    &lt;/bang&gt;
  &lt;/foo&gt;')
</code></pre>

<p>Then the function should transform the document such that only child nodes with a name specified in $includedNodes are returned. </p>

<p>Example <code>local:apply-node-includes($doc, 'baz')</code> would return</p>

<pre><code>&lt;foo a="b"&gt;
  &lt;baz&gt;1&lt;/baz&gt;
&lt;/foo&gt;
</code></pre>

<p>Example <code>local:apply-node-includes($doc, ('bar','bang')))</code> would return</p>

<pre><code>&lt;foo a="b"&gt;
  &lt;bar&gt;hello&lt;/bar&gt;
  &lt;bang&gt;
    &lt;text&gt;world&lt;/text&gt;
  &lt;/bang&gt;
&lt;/foo&gt;
</code></pre>

<p>I experimented iterating over the nodes, and/or using some form of recursive typeswitch but have so far been unable to get it right. It would be really cool if it worked fully recursively so 'bang.text' would include only grandchildren text nodes and not any siblings of them but maybe that is asking too much!</p>