Groovy: keeping of CR/LF of attributes while serializing XMLSlurper

643 Views Asked by At

I'm new with groovy (a few weeks of experience). Currently I'm trying to process some visual studio .vcproj files using groovy: replacing some paths, that will be found by a regexp patterns. This works fine for me.

To write the changes to the file, I'm using the

XmlUtil.serialize(slurper, writer)

method, where

def writer = new FileWriter(outputFile)

and

def slurper = new XmlSlurper(keepIgnorableWhitespace:true).parse(it)

This also works fine, except one thing. In the original vcproj file each attribute is in a separate line, like:

<Configurations>
        <Configuration
            Name="Debug|Win32"
            OutputDirectory="$(ConfigurationName)"
            IntermediateDirectory="$(ConfigurationName)"
            ConfigurationType="1"
            InheritedPropertySheets="..\..\..\..\Test_Debug.vsprops"
            CharacterSet="2"
            >

but after calling the serialize() method of the XMLUtil class, the whole output is stored in one line:

<Configurations>
        <Configuration Name="Debug|Win32" InheritedPropertySheets="..\..\..\..\Test_Debug.vsprops" OutputDirectory="$(ConfigurationName)" IntermediateDirectory="$(ConfigurationName)" ConfigurationType="1" CharacterSet="2">

for the XMS parser this should be not a problem, but in the postprocessing some perl scripts use this vcproj file and they complain about missing CR/LF within the attribute line.

So is there any easy possibility to configure the XMLslurper or the serialize-class to keep the CR/LF in between of each attributes?

1

There are 1 best solutions below

2
On

I doubt there is any easy way to format groovy's xml output to that level. Since the output is a valid XML, can't you use somekind of perl XML parser?

Other than that, you can try to match the attributes with a regex and add a line break to them. A very ugly hack:

import groovy.xml.XmlUtil

def original = '''<Configurations>
        <Configuration
            Name="Debug|Win32"
            OutputDirectory="$(ConfigurationName)"
            IntermediateDirectory="$(ConfigurationName)"
            ConfigurationType="1"
            InheritedPropertySheets="..\\..\\..\\..\\Test_Debug.vsprops"
            CharacterSet="2"
            >
        </Configuration>
    </Configurations>
            '''

parsed = new XmlParser().parseText original

println XmlUtil.serialize(parsed).replaceAll(/[a-zA-Z]*="[^\"]*"/) {
    "\n" + it 
}

will print:

<?xml 
version="1.0" 
encoding="UTF-8"?><Configurations>
  <Configuration 
Name="Debug|Win32" 
OutputDirectory="$(ConfigurationName)" 
IntermediateDirectory="$(ConfigurationName)" 
ConfigurationType="1" 
InheritedPropertySheets="..\..\..\..\Test_Debug.vsprops" 
CharacterSet="2"/>
</Configurations>