Return to Snippet

Revision: 64912
at October 4, 2013 04:00 by thedark


Initial Code
public static class XmlDocumentExtensions {
	public static XmlCDataSection[] CreateCDataSections(this XmlDocument doc, string text) {
		if (text.Contains("]]>")) {
			var parts = text.Split(new[] { "]]>" }, StringSplitOptions.None);
			
			XmlCDataSection[] sections = new XmlCDataSection[parts.Length];
		
			var part = parts[0];
			sections[0] = doc.CreateCDataSection(string.Format("{0}]]", part));
			
			int i = 1;
			
			for (; i < parts.Length - 1; ++i) {
				part = parts[i];
				sections[i] = doc.CreateCDataSection(string.Format(">{0}]]", part));
			}
			
			part = parts[i];
			sections[i] = doc.CreateCDataSection(string.Format(">{0}", part));
		
			return sections;
		} else {
			return new[] { doc.CreateCDataSection(text) };
		}
	}
}

Initial URL

                                

Initial Description
XmlDocument will not behave when you try to CreateCDataSection passing it a string that contains "]]>"

This extension method returns an array of XmlCDataSection, each of which will contain the parts separated by "]]" and ">". Example:

For the string "This string contains ]]>, and ]]> is invalid within CData sections", the return value will be an array containing the following XmlCDataSections:

"This string contains ]]"
">, and ]]"
"> is invalid within CData sections"

which works beautifully.

Optimizations are welcome.

Initial Title
XmlDocument extension method to create CData sections with CData terminators inside

Initial Tags
xml, extension

Initial Language
C#