Groovy 中的 UnEscape Xml

UnEscape Xml in Groovy

我正在尝试 UnEscape xml in Groovy :

<student><age value="20"></age></student>

 <student><age value="20"></age></student>

但我找不到任何可以完成此任务的库。我尝试使用 groovy.json.StringEscapeUtils.unescapeJavaScript 但它没有帮助。

有一个库 groovy.xml.XmlUtilescapeXml 方法但没有 unescape 方法。

我的使用目的是在 Elasticsearch v1.3.2 中使用这个 groovy 脚本,其中包含 groovy-all-2.3.2.jar

有什么建议吗?

不是最有效和最完整的解决方案,但我认为它可以完成工作:

def s = '&lt;student&gt;&lt;age value=&quot;20&quot;&gt;&lt;/age&gt;&lt;/student&gt;'

def u = s.replaceAll(/&lt;/, '<')
         .replaceAll(/&gt;/, '>')
         .replaceAll(/&quot;/, '"')
         .replaceAll(/&apos;/, "'")
         .replaceAll(/&amp;/, '&')

assert u == '<student><age value="20"></age></student>'

为此,您可以只使用 apache 中的 commons-lang。

// 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.StringEscapeUtils

def xml = '&lt;student&gt;&lt;age value=&quot;20&quot;&gt;&lt;/age&gt;&lt;/student&gt;'

def unescaped = StringEscapeUtils.unescapeXml(xml)

比自己编写和维护更容易 ;-)

这是一个使用内置 XmlSlurper class 且无需额外库的技巧:

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

结果:'X & Y < Z'