views:

250

answers:

2

Hello,

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

+3  A: 

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)
Right. The problem is that loading an XML file does not trigger GString evaluation.
Robert Munteanu
Thank's for your answer !I create a template with a fileReader open on my xmlFile, and it works now =)Have a good day
A: 

Currently templating is the approach. But you might want to keep an eye on this issue in JIRA GROOVY-2505. It is a feature request to convert a String to a GString in cases when the string is read from an external source:

Several times it has been asked on the mailing list on how to either convert a String to a GString or to evaluate a String as a GString. The need arises when a String comes in from an external source and contains a GString expression, for example an XML file or a Configuration file. Currently one needs to either invoke the GroovyShell or the SimpleTemplateEngine to accomplish the task. In both cases this takes several lines of code and is not intuitively obvious. One could ether add a GDK method to String such as "evaluate" (which in my humble opinion would be the nicest) or provide a conversion of the form "String as GString"

Brian