UnEscape Xml in Groovy UnEscape Xml in Groovy elasticsearch elasticsearch

UnEscape Xml in Groovy


You can just use commons-lang from apache for this.

// For Grails (2), add:////     compile 'org.apache.commons:commons-lang3:3.3'//// to your build config. For a groovy script, we can do:@Grab('org.apache.commons:commons-lang3:3.3')import org.apache.commons.lang3.StringEscapeUtilsdef xml = '<student><age value="20"></age></student>'def unescaped = StringEscapeUtils.unescapeXml(xml)

Easier than writing and maintaining your own ;-)


Not the most efficient and complete solution but I think it will do the job:

def s = '<student><age value="20"></age></student>'def u = s.replaceAll(/</, '<')         .replaceAll(/>/, '>')         .replaceAll(/"/, '"')         .replaceAll(/&apos;/, "'")         .replaceAll(/&/, '&')assert u == '<student><age value="20"></age></student>'


Here's a trick using the built-in XmlSlurper class and no additional libraries:

value = "X & Y < Z"// wrap the string in made up tags to create// well-enough-formed XML for the XmlSlurperxml = "<foo>${value}</foo>"println xmlroot = new XmlSlurper().parseText(xml)root.toString()

Result: 'X & Y < Z'