0

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?

Simon
  • 97
  • 3
  • 13
  • What you first tried (creating new, setting property, then parsing) seems valid to me. `setKeepIgnorableWhiteSpace()` returns void, so you definitely can't chain the calls. – Daniel Mar 17 '23 at 20:33
  • @Daniel Yes, thats what I though too. But using my first example, when it gets to the rootNode.someThing.each() line it errors out with - No such property: someThing for class: groovy.util.XmlSlurper. It seems the result of the parsing is empty. – Simon Mar 20 '23 at 10:36

1 Answers1

1

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.

Daniel
  • 3,312
  • 1
  • 14
  • 31
  • Thank you very much for pointing me in the right direction. That does indeed work splendidly. – Simon Mar 21 '23 at 14:17