为了能正常输出XML格式的内容,必须要对不被XML允许的那些特殊字符进行转换。本文介绍的正是如何使用C#判断XML字符串是否含特殊字符并进行转换。
以下是几个特殊字符的对应实体。
|
< |
< |
小于号 |
|
> |
> |
大于号 |
|
& |
& |
和 |
|
' |
' |
单引号 |
|
" |
" |
双引号 |
在C#中,直接调用C#提供的方法,保存之后就会自动将特殊字符转为对应实体:
string s =System.Security.SecurityElement.Escape(s);
或者
将内容放在<![CDATA[ ]]>中,例如<![CDATA[2]]> ,CDATA里面的内容在XmlDocument 解析时会自动忽略掉
如果是很多有区域都有特殊内容,可以参考下面的代码通过函数来实现替换。
其实挺简单,只需用下面的这个函数,即可判断及转换XML字符串里的特殊字符。

核心代码
/// <summary>
/// Turns a string into a properly XML Encoded string.
/// Uses simple string replacement.
///
/// Also see XmlUtils.XmlString() which uses XElement
/// to handle additional extended characters.
/// </summary>
/// <param name="text">Plain text to convert to XML Encoded string</param>
/// <param name="isAttribute">
/// If true encodes single and double quotes, CRLF and tabs.
/// When embedding element values quotes don't need to be encoded.
/// When embedding attributes quotes need to be encoded.
/// </param>
/// <returns>XML encoded string</returns>
/// <exception cref="InvalidOperationException">Invalid character in XML string</exception>
public static string XmlString(string text, bool isAttribute = false)
{
var sb = new StringBuilder(text.Length);
foreach (var chr in text)
{
if (chr == '<')
sb.Append("<");
else if (chr == '>')
sb.Append(">");
else if (chr == '&')
sb.Append("&");
// special handling for quotes
else if (isAttribute && chr == '"')
sb.Append(""");
else if (isAttribute && chr == ''')
sb.Append("'");
// Legal sub-chr32 characters
else if (chr == 'n')
sb.Append(isAttribute ? "
" : "n");
else if (chr == 'r')
sb.Append(isAttribute ? "
" : "r");
else if (chr == 't')
sb.Append(isAttribute ? "	" : "t");
else
{
if (chr < 32)
throw new InvalidOperationException("Invalid character in Xml String. Chr " +
Convert.ToInt16(chr) + " is illegal.");
sb.Append(chr);
}
}
return sb.ToString();
}










