Valerie R
Valerie R

Reputation: 1817

Groovy SimpleTemplateEngine and XML array variables

We have an app using Groovy SimpleTemplateEngine to generate text documents. The input is a parsed XML document, and we can generally reference any of these fields from expressions in the template:

def xml = new XmlParser().parseText(xmldocument)
def engine = new SimpleTemplateEngine()
def script = new File(template_file).text
def vars = [xml: xml, ... ]
output = engine.createTemplate(script).make(vars).toString()

In the template script, we reference elements from the XML document using a Groovy expression syntax like this: Hello ${xml.FirstName} (assuming "FirstName" is part of the XML parsed above).

The problem we're having is understanding the syntax to use when referencing items in an XML array. For example, we have XML like this:

<Contact>
  <Name>111</Name>
  <Phone>111</Phone>
</Contact>
<Contact>
  <Name>222</Name>
  <Phone>222</Phone>
</Contact>

What would be the syntax of the expression in the template file that would let us reference (say) the Name and Phone of the second contact? We've tried variations on ${xml.Contact[1].Name} but this doesn't seem to work.

Upvotes: 0

Views: 620

Answers (1)

tim_yates
tim_yates

Reputation: 171114

Given the xml (corrected to have </Phone> close tags:

def xmldocument = '''<Contacts>
                    |    <Contact>
                    |        <Name>111</Name>
                    |        <Phone>111</Phone>
                    |    </Contact>
                    |    <Contact>
                    |        <Name>222</Name>
                    |        <Phone>222</Phone>
                    |    </Contact>
                    |</Contacts>'''.stripMargin()    

def xml = new XmlParser().parseText(xmldocument)

And the template:

def script = 'Hello ${xml.Contact[1].Name.text()}'

Then you can do:

import groovy.text.*

def engine = new SimpleTemplateEngine()
def vars = [xml: xml]
output = engine.createTemplate(script).make(vars).toString()

And

assert output == 'Hello 222'

Will pass

Upvotes: 1

Related Questions