Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy String Concatenation

Tags:

string

groovy

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.

like image 797
XanderLynn Avatar asked Jun 18 '09 03:06

XanderLynn


People also ask

How do I concatenate strings in Groovy?

The concatenation of strings can be done by the simple '+' operator. Parameters − The parameters will be 2 strings as the left and right operand for the + operator.

How do you concatenate 2 strings?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.

Can you use += to concatenate strings?

The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b .

What is ${} in Groovy?

String interpolation. Any Groovy expression can be interpolated in all string literals, apart from single and triple-single-quoted strings. Interpolation is the act of replacing a placeholder in the string with its value upon evaluation of the string. The placeholder expressions are surrounded by ${} .


1 Answers

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)"
like image 134
Ted Naleid Avatar answered Oct 11 '22 08:10

Ted Naleid