作者:手机用户2602918323 | 来源:互联网 | 2023-09-15 16:00
xml字符串拼接的时候如果不考虑用户输入信息包含大于小于的情况,会导致系统崩溃.所以如果是纯xml拼接,一定要将xml的敏感字符给转义掉或者用包括起来.xml敏感的字符包含下面几
xml字符串拼接的时候如果不考虑用户输入信息包含大于小于的情况, 会导致系统崩溃.
所以如果是纯xml拼接,一定要将 xml的敏感字符给转义掉或者 用包括起来.
xml敏感的字符包含下面几个. <, > , ", &#39;, &
微软底层已经为我们做了一些工作, 我们只需要调用既可以了.
方法如下.
var safexml &#61; System.Security.SecurityElement.Escape(xml);
用法如下
var safetxt &#61; System.Security.SecurityElement.Escape(txt);
var xml &#61; ""&#43; safetxt&#43;""
System.Security.SecurityElement.Escape 我们反编译其源代码可以看到是
如果不想引用这个dll, 可以把下面的源代码复制过来处理一下.
static SecurityElement()
{s_tagIllegalCharacters &#61; new char[] { &#39; &#39;, &#39;<&#39;, &#39;>&#39; };s_textIllegalCharacters &#61; new char[] { &#39;<&#39;, &#39;>&#39; };s_valueIllegalCharacters &#61; new char[] { &#39;<&#39;, &#39;>&#39;, &#39;"&#39; };s_escapeStringPairs &#61; new string[] { "<", "<", ">", ">", "\"", """, "&#39;", "'", "&", "&" };s_escapeChars &#61; new char[] { &#39;<&#39;, &#39;>&#39;, &#39;"&#39;, &#39;\&#39;&#39;, &#39;&&#39; };
}public static string Escape(string str)
{if (str &#61;&#61; null){return null;}StringBuilder builder &#61; null;int length &#61; str.Length;int startIndex &#61; 0;while (true){int num2 &#61; str.IndexOfAny(s_escapeChars, startIndex);if (num2 &#61;&#61; -1){if (builder &#61;&#61; null){return str;}builder.Append(str, startIndex, length - startIndex);return builder.ToString();}if (builder &#61;&#61; null){builder &#61; new StringBuilder();}builder.Append(str, startIndex, num2 - startIndex);builder.Append(GetEscapeSequence(str[num2]));startIndex &#61; num2 &#43; 1;}
}private static string GetEscapeSequence(char c)
{int length &#61; s_escapeStringPairs.Length;for (int i &#61; 0; i < length; i &#43;&#61; 2){string str &#61; s_escapeStringPairs[i];string str2 &#61; s_escapeStringPairs[i &#43; 1];if (str[0] &#61;&#61; c){return str2;}}return c.ToString();
}