Search code examples
filegroovygstring

Replace GString tags in a file


i've got a word document saved in xml format. In this document, there are some GString Tag like $name.

In my groovy code, i load the xml file to replace this GString tag like this:

    def file = new File ('myDocInXml.xml')
    def name = 'myName'
    file.eachLine { line ->
        println line
    }

But it doesn't works. The GString Tag doesn't be replaced by my variable 'name'.

Could anyone help me ?

THX


Solution

  • Better to use a templating here. Load the xmml file as a template and create a binding to replace the placeholders. A simple example could be like

    def xml='''
    <books>
    <% names.each { %>
    <book>
     $it
    </book>
    <%}%>
    
    </books>
    '''
    def engine=new groovy.text.SimpleTemplateEngine()
    def template=engine.createTemplate(xml)
    def binding=[names:['john','joe']]
    template.make(binding)