title: Groovy edit XML file, keep comments, line breaks
body: <p>I would like to edit an existing XML file while preserving it's original layout. This includes new lines, comments etc. Editing is composed of finding elements inside the XML and modifying the text value.</p>
  
  <p>My first try was using XMLParser with XmlUtil.serialize but that does not meet the requirement. </p>
  
  <p>Anyone is aware of any alternative to XMLParser where edits are "in place" of the original XML string? If not, perhaps there is a library that performs search using XPath/GPath and just return the location of the find so I can do StringBuilder.replace.</p>
  
  <p><strong>EDIT</strong>:</p>
  
  <p>For now I made this function, to find string indexes of XML node (that I can find using xpath) then I am doing replace on the indexes. Works fine for simple nodes
  &lt;node>value&lt;/node>:</p>
  
  <pre><code>def find_location_by_node(xmlString, root_xml, node)
  {
      current_index = 0;
  
      for(current_node in root_xml.depthFirst())
      {
        node_name = current_node.name().getLocalPart()
        current_index = xmlString.indexOf('&lt;' + node_name, current_index);
  
        if(current_node == node)
        {
          end_tag = '&lt;/' + node_name + '&gt;';
          end_tag_index = xmlString.indexOf(end_tag, current_index) + end_tag.length();
  
          return [current_index, end_tag_index];
        }
      }
  
    return -1;
  }
  </code></pre>