public static string? EscapeXml()

in src/AlibabaCloud.OSS.V2/Transform/Functions.cs [323:397]


        public static string? EscapeXml(string? str)
        {
            if (str == null)
                return null;

            StringBuilder? sb = null;

            var strLen = str.Length;
            var newIndex = 0;

            while (true)
            {
                var index = -1;
                var s = "";

                for (var idx = newIndex; idx < strLen; idx++)
                {
                    var ch = str[idx];

                    switch (ch)
                    {
                        case '<':
                            s = "&lt;";
                            index = idx;
                            break;
                        case '>':
                            s = "&gt;";
                            index = idx;
                            break;
                        case '\"':
                            s = "&quot;";
                            index = idx;
                            break;
                        case '\'':
                            s = "&apos;";
                            index = idx;
                            break;
                        case '&':
                            s = "&amp;";
                            index = idx;
                            break;
                        default:
                            if (ch < 0x20)
                            {
                                s = $"&#{(int)ch:D2};";
                                index = idx;
                            }

                            break;
                    }

                    if (index != -1) break;
                }

                if (index == -1)
                {
                    if (sb == null)
                    {
                        return str;
                    }
                    else
                    {
                        sb.Append(str, newIndex, strLen - newIndex);
                        return sb.ToString();
                    }
                }
                else
                {
                    sb ??= new();
                    sb.Append(str, newIndex, index - newIndex);
                    sb.Append(s);
                    newIndex = index + 1;
                }
            }
        }