/// <summary>Replaces invalid XML characters in a string with their valid XML equivalent.</summary> /// <returns>The input string with invalid characters replaced.</returns> /// <param name="str">The string within which to escape invalid characters. </param> public static string Escape(string str) { if (str == null) { return(null); } StringBuilder stringBuilder = null; int length = str.Length; int num = 0; while (true) { int num2 = str.IndexOfAny(SecurityElement.s_escapeChars, num); if (num2 == -1) { break; } if (stringBuilder == null) { stringBuilder = new StringBuilder(); } stringBuilder.Append(str, num, num2 - num); stringBuilder.Append(SecurityElement.GetEscapeSequence(str[num2])); num = num2 + 1; } if (stringBuilder == null) { return(str); } stringBuilder.Append(str, num, length - num); return(stringBuilder.ToString()); }
/// <summary>将字符串中的无效 XML 字符替换为与其等效的有效 XML 字符。</summary> /// <returns>包含无效字符的输入字符串被替换。</returns> /// <param name="str">要对其中的无效字符进行转义的字符串。</param> public static string Escape(string str) { if (str == null) { return((string)null); } StringBuilder stringBuilder = (StringBuilder)null; int length = str.Length; int startIndex = 0; while (true) { int index = str.IndexOfAny(SecurityElement.s_escapeChars, startIndex); if (index != -1) { if (stringBuilder == null) { stringBuilder = new StringBuilder(); } stringBuilder.Append(str, startIndex, index - startIndex); stringBuilder.Append(SecurityElement.GetEscapeSequence(str[index])); startIndex = index + 1; } else { break; } } if (stringBuilder == null) { return(str); } stringBuilder.Append(str, startIndex, length - startIndex); return(stringBuilder.ToString()); }