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

CSharp examples for System.Xml:XML String

Description

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

Demo Code


using System.Xml.Serialization;
using System.IO;//from   w  w  w .  ja v a2s . 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 "parsed character data".
        /// </summary>
        /// <param name="input">the text to encode</param>
        /// <returns>the encoded text</returns>
        public static string EncodePCDATA(string input)
        {
            string result;
            result = Regex.Replace(input, "&", "&amp;");    // Do this one first so "&"s in replacements pass through unchanged.
            result = Regex.Replace(result, "<", "&lt;");
            result = Regex.Replace(result, ">", "&gt;");
            result = Regex.Replace(result, "-", "&#x2d;");   // Because XML comments are "--comment--".
            return result;
        }
}

Related Tutorials