Skip to content

Instantly share code, notes, and snippets.

@devilelephant
Created September 13, 2013 18:48
Show Gist options
  • Save devilelephant/6554529 to your computer and use it in GitHub Desktop.
Save devilelephant/6554529 to your computer and use it in GitHub Desktop.
Groovy XML Markup Builder Tricks: CDATA, declaration, comments
def out = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(out)
// MarkupBuilder gives us an instance of MarkupBuilderHelper named 'mkp'
// MarkupBuilderHelper has several helpful methods
xml.mkp.xmlDeclaration(version: "1.0", encoding: "utf-8")
xml.example {
a {
b {
mkp.comment('a comment')
c('normal elements')
}
}
d {
xml.mkp.yieldUnescaped("<![CDATA[Example of text in a CDATA block]]>")
}
}
assert out.toString() == '''
<?xml version='1.0' encoding='utf-8'?>
<example>
<a>
<b><!-- a comment -->
<c>normal elements</c>
</b>
</a>
<d><![CDATA[Example of text in a CDATA block]]></d>
</example>
'''.trim()
@devilelephant
Copy link
Author

I wrote this on an old blog post and about once a year someone says thanks so I figured might as well move it to more appropriate place for easy sharing.

@rcr866
Copy link

rcr866 commented Aug 25, 2014

thanks!

@JasonArm
Copy link

Thanks.
(Bit more than a year 😉 )

@Drezil
Copy link

Drezil commented Nov 16, 2018

Thanks.
(we can settle on 18 months as average .. 😉 )

@gregorydickson
Copy link

Thanks

@slogic
Copy link

slogic commented Dec 14, 2023

Please, update example if "Example of text" also contains cdata section. Rigth now it is error prone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment