title: Deleting nodes in XML using Xpath in Groovy
body: <p>I've got this Groovy code working to delete nodes using xpath strings, but I'm having problems deleting nodes where the xpath results in multiple node instances.</p>
  
  <p><strong>Sample XML...</strong></p>
  
  <pre><code>&lt;root&gt;
    &lt;element1&gt;foo&lt;/element1&gt;
    &lt;element2&gt;bar&lt;/element2&gt;
    &lt;items&gt;
       &lt;item&gt;
         &lt;name&gt;a&lt;/name&gt;
         &lt;desc&gt;b&lt;/desc&gt;
       &lt;item&gt;
       &lt;item&gt;
          &lt;name&gt;c&lt;/name&gt;
          &lt;desc&gt;x&lt;/desc&gt;
       &lt;/item&gt;
    &lt;/items&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p><strong>Code to delete nodes...</strong></p>
  
  <pre><code>def resource = XmlSlurper().parseText(xml)
  def xpathsToDelete = ['/root/element1','/root/items/item/name']
   xpathsToDelete.each {
       def pathTokens = it.path.tokenize '/'
       def currentNode = resource
       if ( currentNode.name() == pathTokens.first() ) { 
         def xpath = pathTokens.tail().join '/'
         currentNode = currentNode."${xpath}"
         currentNode.replaceNode{}
       }
  }
  </code></pre>
  
  <p>The above code removes the node <code>element1</code> using xpath <code>/root/element1</code>, which evaluates to a single node, but does not work for <code>/root/items/name</code> which evaluates to multiple nodes.</p>