XmlDocument extension method to create CData sections with CData terminators inside


/ Published in: C#
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. public static class XmlDocumentExtensions {
  2. public static XmlCDataSection[] CreateCDataSections(this XmlDocument doc, string text) {
  3. if (text.Contains("]]>")) {
  4. var parts = text.Split(new[] { "]]>" }, StringSplitOptions.None);
  5.  
  6. XmlCDataSection[] sections = new XmlCDataSection[parts.Length];
  7.  
  8. var part = parts[0];
  9. sections[0] = doc.CreateCDataSection(string.Format("{0}]]", part));
  10.  
  11. int i = 1;
  12.  
  13. for (; i < parts.Length - 1; ++i) {
  14. part = parts[i];
  15. sections[i] = doc.CreateCDataSection(string.Format(">{0}]]", part));
  16. }
  17.  
  18. part = parts[i];
  19. sections[i] = doc.CreateCDataSection(string.Format(">{0}", part));
  20.  
  21. return sections;
  22. } else {
  23. return new[] { doc.CreateCDataSection(text) };
  24. }
  25. }
  26. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.