Groovy中的UnEscape Xml

时间:2015-08-19 14:00:16

标签: xml groovy elasticsearch escaping

我正在尝试使用Groovy中的UnEscape xml:

<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

有什么建议吗?

3 个答案:

答案 0 :(得分:5)

你可以使用apache-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)

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

答案 1 :(得分:3)

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

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>'

答案 2 :(得分:2)

这里有一个使用内置XmlSlurper类的技巧,没有其他库:

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()

结果:&#39; X&amp; Y&lt; ž&#39;

相关问题