Groovy xmlSlurper to remove empty fields

时间:2018-02-26 17:47:03

标签: groovy nsxmlparser xmlslurper

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

0 个答案:

没有答案