Home > Enterprise >  Groovy script to convert xml to csv keeping spaces intact
Groovy script to convert xml to csv keeping spaces intact

Time:06-01

I'm trying to write a groovy script to convert an xml into a csv file. The input xml:

<Structure>
    <Header>
        <PlanNumber>123456</PlanNumber>
        <HeaderRec>ABC</HeaderRec>
        <Plan>1234</Plan>
        <Filler>                 </Filler>
        <CompanyName>Dummy</CompanyName>
    </Header>
    <Records>
        <Record1>
            <Field1>ABCD</Field1>
            <Field2>ABCD</Field2>
            <Field3>ABCD</Field3>
            <Field4>ABCD</Field4>
            <Field5>ABCD</Field5>
            <Filler>          </Filler> 
        </Record1>
        <Record2>
            <Field1>ABCD</Field1>
            <Field2>ABCD</Field2>
            <Filler>         </Filler>
            <Field4>ABCD</Field4>
            <Field5>ABCD</Field5>
            <Filler>          </Filler> 
        </Record2>      
    </Records>
</Structure>

My groovy script:

def content = new XmlSlurper().parseText(input)
def header = content.Header.children().collect().join(' ')
    
def csv = content.Records.children().inject(header){result, row -> [result,row.children().collect().join(' ')].join("\n")}
println csv.toString()

This is the output I'm getting:

123456 ABC 1234  Dummy
ABCD ABCD ABCD ABCD ABCD 
ABCD ABCD  ABCD ABCD 

The script is ignoring the spaces in the filler fields. My requirement is that any spaces in the xml fields should be intact in the csv. That is, if there are 7 whitespaces in the field, the same should be maintained in the csv. As of now, the spaces are being ignored. Can you please help me. Do I need to change my approach?

CodePudding user response:

Use keepWhitespace:true. That should resolve it.

def content = new XmlSlurper(keepWhitespace:true).parseText(input)

  • Related