XML CDATA and escaping

By: on October 25, 2007

XML’s syntax for CDATA looks like this:

  <![CDATA[some text]]>

Tag syntax within a CDATA section is suspended, so this is well-formed XML:

  <![CDATA[some <more> text]]>

even though it looks like the “<more>” tag is unclosed.

There’s only one thing you can’t say in a CDATA section: “]]>”. But there’s a trick to save us, even here. To print an arbitrary string in a CDATA enclosure, replace each instance of “]]>” with “]]]]><![CDATA[>”, and then put the normal “<![CDATA[“/”]]>” brackets around it:

  my ]]> text


  <![CDATA[my ]]]]><![CDATA[> text]]>


  1. Chui Tey says:

    I’m (pleasantly) surprised that Google Feed Reader actually formatted your post correctly!

  2. Javier says:


Leave a Reply

Your email address will not be published.


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>