title: replace XmlSlurper tag with arbitrary XML
body: <p>I am trying to replace specific XmlSlurper tags with arbitrary XML strings. The best way I have managed to come up with to do this is:</p>
  
  <p>#!/usr/bin/env groovy</p>
  
  <pre><code>import groovy.xml.StreamingMarkupBuilder
  
  def page=new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parseText("""
  &lt;html&gt;
  &lt;head&gt;&lt;/head&gt;
  &lt;body&gt;
  &lt;one attr1='val1'&gt;asdf&lt;/one&gt;
  &lt;two /&gt;
  &lt;replacemewithxml /&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  """.trim())
  
  import groovy.xml.XmlUtil
  
  def closure
  closure={ bind,node-&gt;
    if (node.name()=="REPLACEMEWITHXML") {
      bind.mkp.yieldUnescaped "&lt;replacementxml&gt;sometext&lt;/replacementxml&gt;"
    } else {
      bind."${node.name()}"(node.attributes()) {
        mkp.yield node.text()
        node.children().each { child-&gt;
   closure(bind,child)
        }
      }
    }
  }
  println XmlUtil.serialize(
    new StreamingMarkupBuilder().bind { bind-&gt;
      closure(bind,page)
    }
  )
  </code></pre>
  
  <p>However, the only problem is the text() element seems to capture <em>all</em> child text nodes, and thus I get:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;HTML&gt;asdf&lt;HEAD/&gt;
     &lt;BODY&gt;asdf&lt;ONE attr1="val1"&gt;asdf&lt;/ONE&gt;
        &lt;TWO/&gt;
        &lt;replacementxml&gt;sometext&lt;/replacementxml&gt;
     &lt;/BODY&gt;
  &lt;/HTML&gt;
  </code></pre>
  
  <p>Any ideas/help much appreciated.</p>
  
  <p>Thank you!
  Misha</p>
  
  <p>p.s. Also, out of curiosity, if I change the above to the "Groovier" notation as follows, the groovy compiler thinks I am trying to access the ${node.name()} member of my test class. Is there a way to specify this is not the case while still not passing the actual builder object? Thank you! :)</p>
  
  <pre><code>def closure
  closure={ node-&gt;
    if (node.name()=="REPLACEMEWITHXML") {
      mkp.yieldUnescaped "&lt;replacementxml&gt;sometext&lt;/replacementxml&gt;"
    } else {
      "${node.name()}"(node.attributes()) {
        mkp.yield node.text()
        node.children().each { child-&gt;
   closure(child)
        }
      }
    }
  }
  println XmlUtil.serialize(
    new StreamingMarkupBuilder().bind { 
      closure(page)
    }
  )
  </code></pre>