Groovy String Concatenation

21,917

I think it can be a lot easier in groovy than the currently accepted answer. The collect and join methods are built for this kind of thing. Join automatically takes care of concatenation and also does not put the trailing comma on the string

def names = row.column.collect { it.attributes()['name'] }.join(",")
def values = row.column.collect { it.values() }.join(",")
def result = "INSERT INTO tablename($names) VALUES($values)"
Share:
21,917
XanderLynn
Author by

XanderLynn

Sometimes a void is the best option.

Updated on December 12, 2020

Comments

  • XanderLynn
    XanderLynn over 3 years

    Current code:

    row.column.each(){column ->
        println column.attributes()['name']
        println column.value()
    }
    

    Column is a Node that has a single attribute and a single value. I am parsing an xml to input create insert statements into access. Is there a Groovy way to create the following structured statement:

    Insert INTO tablename (col1, col2, col3) VALUES (1,2,3)
    

    I am currently storing the attribute and value to separate arrays then popping them into the correct order.

  • XanderLynn
    XanderLynn almost 15 years
    This worked perfectly! Because my setup was table.row.column I used ${table.attributes()['name']} to retrieve the tablename
  • Dónal
    Dónal over 14 years
    In Groovy you can append to a StringBuilder using '<<' rather than "append()" which makes the code a lot more readable IMO