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
3
  • 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! Commented Feb 26, 2018 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 - groovy-lang.org/processing-xml.html Commented Feb 26, 2018 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." Commented Feb 26, 2018 at 19:54

1 Answer 1

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{}
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.