How to use XMLSlurper and setKeepIgnorableWhiteSpace()

66 views Asked by At

I have a piece of Grails code which is downloading an XML file, parsing it, making some changes, then writing it back again.

def xmlFile = simpleSftpService.downloadFile('theFile.xml')    
def rootNode = new XmlSlurper().parse(xmlFile)
rootNode.someThing.each(){
    it.thingy='It should be this'
}

def fileName="MyNew.xml"
File writer = File.createTempFile('tempFile', '.xml')
def builder = new StreamingMarkupBuilder()
        writer << builder.bind {
            mkp.yield rootNode
        }
InputStream inputStream = new BufferedInputStream(new FileInputStream(writer))
def storeFile = simpleSftpService.uploadFile(inputStream, fileName)

This all works fine, except I lose all the whitespace in the resultant file. So to overcome this I am trying to use the following code :-

def rootNode= new XmlSlurper()
rootNode.setKeepIgnorableWhiteSpace(true)
rootNode.parse(xmlFile)

Which doesn't work in that it produces null. So I tried :-

def rootNode=XmlSlurper()setKeepIgnorableWhiteSpace(true).parse(xmlFile)

but that gives me an error :-

java.lang.NullPointerException: Cannot invoke method parse() on null object

How can I use setKeepIgnorableWhiteSpace() to keep the formatting in my XML?

1

There are 1 answers

1
Daniel On

This should work:

def slurper = new XmlSlurper()
slurper.setKeepIgnorableWhiteSpace(true)
def rootNode = slurper.parse(xmlFile)
rootNode.someThing?.each { ...
...etc.

Problem was that you were setting rootNode to the XmlSlurper rather than to the results of the parse.