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