title: Is there a better way to find ancestors in xml using Groovy Gpath?
body: <p>Please see my below groovy code which is working as expected - but wondered if there is a better way to get ancestor info?</p>
  
  <p>My sample xml record:</p>
  
  <pre><code>String record = '''
  &lt;collections&gt;
    &lt;material&gt;
      &lt;books&gt;
        &lt;title&gt;Italy&lt;/title&gt;
      &lt;/books&gt;
    &lt;/material&gt;
    &lt;material&gt;
      &lt;books&gt;
        &lt;title&gt;Greece&lt;/title&gt;
      &lt;/books&gt;  
    &lt;/material&gt;
    &lt;material&gt;
      &lt;books&gt;
        &lt;author&gt;Germany&lt;/author&gt;
      &lt;/books&gt;  
    &lt;/material&gt;  
    &lt;material&gt;
      &lt;cd&gt;
        &lt;author&gt;France&lt;/author&gt;
      &lt;/cd&gt;  
    &lt;/material&gt;  
  &lt;/collections&gt;
  '''
  </code></pre>
  
  <p>I am wondering if there is any better way to optimise this bit of getting the ancestors ?</p>
  
  <pre><code>GPathResult extractedMaterialBlocks = extractAllMaterialBlocks(record)
  String finalXml = serializeXml(extractedMaterialBlocks.parent().parent(), 'UTF-8') 
  println "finalXml : ${finalXml}"
  </code></pre>
  
  <p>My methods:</p>
  
  <pre><code>GPathResult extractAllMaterialBlocks(String record) {
      GPathResult result = new XmlSlurper().parseText(record)
      return result ? result.'material'?.'books'?.'title'?.findAll { it }  : null
  }
  
  String serializeXml(GPathResult xmlToSerialize, String encoding) {
      def builder = new StreamingMarkupBuilder()
      builder.encoding = encoding
      builder.useDoubleQuotes = true
  
      return builder.bind {
          out &lt;&lt; xmlToSerialize
      }.toString()
  }
  </code></pre>
  
  <p>Output as expected: </p>
  
  <pre><code>&lt;material&gt;
      &lt;books&gt;
        &lt;title&gt;Italy&lt;/title&gt;
      &lt;/books&gt;
  &lt;/material&gt;
  &lt;material&gt;
      &lt;books&gt;
        &lt;title&gt;Greece&lt;/title&gt;
      &lt;/books&gt;  
  &lt;/material&gt;
  </code></pre>