Nov
20
You can’t nest CDATA sections in XML. It’s not allowed. But Steve Claflin, our Java trainer extraordinaire and courseware author figured out a work around.
Nesting CDATA Sections – (workaround)
Imagine you’re starting with this code:
1 2 3 4 5 6 7 | <foo> code here <![CDATA[ escaped code here ]]> more code here </foo> |
You then want to wrap everything inside the foo tag within a CDATA section like this:
1 2 3 4 5 6 7 | <foo><![CDATA[ code here <![CDATA[ escaped code here ]]> more code here ]]></foo> |
But you can’t do that, because the closing of the nested CDATA tag closes the outer CDATA tag leaving you with poorly formed XML.
Here’s the workaround Steve came up with:
1 2 3 4 5 6 7 | <foo><![CDATA[ code here <![CDATA[ escaped code here ]]]]><![CDATA[> more code here ]]></foo> |
The magic is in line 5 where he splits up the closing CDATA code (i.e., ]]>) using a close and open CDATA tag. This essentially does away with the nested CDATA tag, but keeps the original content whole. Very sweet!
No TweetBacks yet. (Be the first to Tweet this post)





Thanks, it was of gr8 help
May 1st, 2012 at 7:54 am