Why would you need to?
You have to break your data into pieces to conceal the ]]>
.
Here's the whole thing:
<![CDATA[]]]]><![CDATA[>]]>
The first <![CDATA[]]]]>
has the ]]
. The second <![CDATA[>]]>
has the >
.
S. Lott's answer is right: you don't encode the end tag, you break it across multiple CDATA sections.
How to run across this problem in the real world: using an XML editor to create an XML document that will be fed into a content-management system, try to write an article about CDATA sections. Your ordinary trick of embedding code samples in a CDATA section will fail you here. You can imagine how I learned this.
But under most circumstances, you won't encounter this, and here's why: if you want to store (say) the text of an XML document as the content of an XML element, you'll probably use a DOM method, e.g.:
XmlElement elm = doc.CreateElement("foo");
elm.InnerText = "<[CDATA[[Is this a problem?]]>";
And the DOM quite reasonably escapes the < and the >, which means that you haven't inadvertently embedded a CDATA section in your document.
Oh, and this is interesting:
XmlDocument doc = new XmlDocument();
XmlElement elm = doc.CreateElement("doc");
doc.AppendChild(elm);
string data = "<![[CDATA[This is an embedded CDATA section]]>";
XmlCDataSection cdata = doc.CreateCDataSection(data);
elm.AppendChild(cdata);
This is probably an ideosyncrasy of the .NET DOM, but that doesn't throw an exception. The exception gets thrown here:
Console.Write(doc.OuterXml);
I'd guess that what's happening under the hood is that the XmlDocument is using an XmlWriter produce its output, and the XmlWriter checks for well-formedness as it writes.
Breaking the CDATA into two is the right solution. The problem is by no means academic. One of systems I am using is exporting XHTML templates to XML file and does not treat CDATA right (it was in tag). This means it was unable to import back its own backups without the trick. Thanks S. Lott.
If anyone is looking for a solution on this, here's an (untested) function that should handle it in PHP.
Never mind, the website seems to edit my lol.