Encode a string so it is safe to use as XML "character data". - CSharp System.Xml

CSharp examples for System.Xml:XML String

Description

Encode a string so it is safe to use as XML "character data".

Demo Code


using System.Xml.Serialization;
using System.IO;//  w  w w  . java 2 s  .c  om
using System.Xml;
using System.Text.RegularExpressions;
using System;

public class Main{
        /// <summary>
        /// Encode a string so it is safe to use as XML "character data".
        /// </summary>
        /// <param name="text">the text to encode</param>
        /// <returns>the encoded text</returns>
        /// <remarks>
        /// This method damages the resulting string, because the sequence "]]&gt;" is forbidden inside
        /// a CDATA section and cannot be escaped or encoded.  Since we can't protect it, we insert a
        /// space between the brackets so it isn't recognized by an XML parser.  C'est la guerre.
        /// </remarks>
      public static string EncodeCDATA(string text)
      {
         Regex cDataCloseTag = new Regex(@"\]\]>");
         return cDataCloseTag.Replace(text, @"] ]>");
      }
}

Related Tutorials