groovygroovyscriptengine

How to concatenate elements of list in a new line in flat file in Groovy script


I am trying to get all the values from following xml into one string splitted by "|"

<n0:SendData xmlns:n0="http://testdata/"
                 xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
    <Operation>Testing1</Operation>
    <InputDataList>
        <InputData>
            <Field>ATTRIBUTE1</Field>
            <Value>1.000</Value>
        </InputData>
        <InputData>
            <Field>ATTRIBUTE2</Field>
            <Value>test</Value>
        </InputData>
        <InputData>
            <Field>ATTRIBUTE3</Field>
        </InputData>
        <InputData>
            <Field>ATTRIBUTE4</Field>
            <Value>testend</Value>
        </InputData>
    </InputDataList>
    <InputDataList>
        <InputData>
            <Field>ATTRIBUTE1</Field>
            <Value>2.000</Value>
        </InputData>
        <InputData>
            <Field>ATTRIBUTE2</Field>
            <Value>test2</Value>
        </InputData>
        <InputData>
            <Field>ATTRIBUTE3</Field>
            <Value>test2end</Value>
        </InputData>
        <InputData>
            <Field>ATTRIBUTE4</Field>
        </InputData>
    </InputDataList>
</n0:SendData>

Code that I came up with:

def xml = new XmlSlurper().parseText(data)

def items = xml.InputDataList.each { node ->
    node.InputData.Field.text() == ""
}.collect { node ->
    node.InputData.with {
        "${InputData.text()}|\n"
    }
}

println items

Which will result in following response

1.000testtestend|

2.000test2testend2|

However I cannot find the way to add "|" after each element of the list, even when the value is empty?

Result I am looking for is as follows

1.000|test||testend

2.000|test2|test2end||


Solution

  • You want to collect the Values for each InputDataList, join them with |:

    def items = xml.InputDataList.collect { node ->
            node.InputData*.Value.join("|")
    }.join("\n")
    

    The each in your original attempt, is a no-op, because the comparison there only heats your room. Do you want to findAll instead?