I’m looking to replace escaped XML sections with CDATA blocks, mainly to improve the readability of XML that unfortunately has to be read by a human.
// Input
def xml = '''
<search>
<search-query>
<nested/<
<xml/<
</search-query>
</search>
'''
def search = new XmlParser().parseText(xml)
def query = search."search-query"
query.replaceNode() {
"search-query"() {
// TODO how can I add a CDATA section here?
//yieldUnescaped("<![CDATA[${query.text()}]]>")
}
}
new XmlNodePrinter(preserveWhitespace:true).print(search)
// Expected
'''
<search>
<search-query>
<![CDATA[<nested/>
<xml/>]]>
</search-query>
</search>
'''
- Performance is not important
- I want to be able to use CDATA on only certain elements
Use this XSLT transformation:
You can replace cdata-section-elements with a space-separated list of element names.