Given an object 'obj' do ToString() on it, and then transform it so that all special XML characters are escaped and return the result. - CSharp System.Xml

CSharp examples for System.Xml:XML String

Description

Given an object 'obj' do ToString() on it, and then transform it so that all special XML characters are escaped and return the result.

Demo Code

//     Copyright (c) Microsoft Corporation.  All rights reserved.
using System.Text;
using System.Diagnostics;
using System;// w  w  w. j a v  a  2 s .  co m

public class Main{
        /// <summary>
        /// Given an object 'obj' do ToString() on it, and then transform it so that all special XML characters are escaped and return the result. 
        /// If 'quote' is true also surround the resulting object with double quotes.
        /// </summary>
        public static string XmlEscape(object obj, bool quote = false)
        {
            string str = obj.ToString();
            StringBuilder sb = null;
            string entity = null;
            int copied = 0;
            for (int i = 0; i < str.Length; i++)
            {
                switch (str[i])
                {
                    case '&':
                        entity = "&amp;";
                        goto APPEND;
                    case '"':
                        entity = "&quot;";
                        goto APPEND;
                    case '\'':
                        entity = "&apos;";
                        goto APPEND;
                    case '<':
                        entity = "&lt;";
                        goto APPEND;
                    case '>':
                        entity = "&gt;";
                        goto APPEND;
                        APPEND:
                        {
                            if (sb == null)
                            {
                                sb = new StringBuilder();
                                if (quote)
                                    sb.Append('"');
                            }
                            while (copied < i)
                                sb.Append(str[copied++]);
                            sb.Append(entity);
                            copied++;
                        }
                        break;
                }
            }

            if (sb != null)
            {
                while (copied < str.Length)
                    sb.Append(str[copied++]);
                if (quote)
                    sb.Append('"');
                return sb.ToString();
            }
            if (quote)
                str = "\"" + str + "\"";
            return str;
        }
}

Related Tutorials