0

I have a code that is removing empty fields using XMLParser, I wonder if could you help me to have a version of the same using xmlSlurper instead.

The code is below:

File doc = new File("C:/Temp/input.xml")

def text = new String(doc.bytes, "UTF-8")

def xml = new XmlParser().parseText( text )

xml.depthFirst().each { 
  if( it.children().size() == 0 ) {
    it.parent().remove( it )
  }
}

def file = new File("C:/Temp/out/test.xml")   
def xmltext = XmlUtil.serialize(xml)
file.write(xmltext,'UTF-8')

So far, my best guess using the XMLSlurper is, but it isn't working:

def xmlSl = new XmlSlurper().parseText(text)
xmlSl.depthFirst().each { 
  if( it.children().size() == 0 ) {
    it.parent().replaceNode { }
  }
}


def fileSl = new File("C:/Temp/out/testSl.xml")   
def xmltextSl = XmlUtil.serialize(xmlSl)
file.write(xmltextSl,'UTF-8')
println xmltextSl
Raul Biondo
  • 17
  • 1
  • 8
  • Hi @SzymonStepniak, I've a lot of codes locally, and I've created this short version only to create a question here but it is far from be simple like this. However, I do expect with a sample on how xmlSlurper could handle this to understand how to expand this use in my code. I hope this makes sense.... Thanks! – Raul Biondo Feb 26 '18 at 18:04
  • I was wondering if you have tried coding something with XmlSlurper? Groovy has a very descriptive documentation about parsing XMLs, it should be pretty straightforward after reading and playing around with docs - http://groovy-lang.org/processing-xml.html – Szymon Stepniak Feb 26 '18 at 19:10
  • My bad @SzymonStepniak, I've tried different ways to do it and the closest I got is the code that I've just included at the beginning of the post. The error message I got on that is: **"[Fatal Error] :2:1: Premature end of file. ERROR: 'Premature end of file.' Exception in thread "main" groovy.lang.GroovyRuntimeException: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 1; Premature end of file."** – Raul Biondo Feb 26 '18 at 19:54

1 Answers1

1

You need to call replace node on empty node instead of calling it on it's parent:

xmlSl.depthFirst().each { 
  if(!it.text()){
     it.replaceNode{}
  }
}
Evgeny Smirnov
  • 2,886
  • 1
  • 12
  • 22