Пример #1
0
        public static string Unescape(string text)
        {
            // We only escape an XML-safe subset of the JavaScript escaped characters,
            // so we can reverse things correctly using JavaScript's Unescape method.
            string result = JavaScriptUtility.Unescape(text);

            return(result);
        }
Пример #2
0
        public static string Escape(string text)
        {
            int length = text.Length;

            StringBuilder sb = new(2 * length);

            for (int i = 0; i < length; i++)
            {
                char ch = text[i];
                if (ch == ' ')
                {
                    // XML attributes will remove leading and trailing spaces and collapse sequences of spaces to a single space.
                    // We don't want that so we have to encode non-safe spaces. It's a safe space if chars before and after are
                    // non-spaces. This also encodes "X%20%20Y" when only one of the spaces needs to be encoded, but that's ok.
                    // See "Attribute-Value Normalization" at https://www.w3.org/TR/REC-xml/#AVNormalize.
                    if (i > 0 && i < length - 1 && text[i - 1] != ' ' && text[i + 1] != ' ')
                    {
                        // A safe space (i.e., surrounded by non-space chars).
                        sb.Append(ch);
                    }
                    else
                    {
                        // Either a leading space, a trailing space, or in a sequence of spaces.
                        sb.Append(JavaScriptUtility.Escape(ch));
                    }
                }
                else if (ch != '%' && ch > ' ' && ch <= '~')
                {
                    // Allow any "printable" char except '%' since that's the JavaScript escape char.
                    sb.Append(ch);
                }
                else
                {
                    // This will be used for control chars, which are invalid in XML, and for higher Unicode chars.
                    sb.Append(JavaScriptUtility.Escape(ch));
                }
            }

            string result = sb.ToString();

            return(result);
        }