我的字符串XML包含一系列特殊字符:
&
egrave;
&
rsquo;
&
rsquo;
&
rsquo;
&
ldquo;
&
rdquo;
&
rsquo
&
agrave;
&
agrave;
Run Code Online (Sandbox Code Playgroud)
我需要在DB中插入字符串中替换此特殊字符,我尝试使用System.Net.WebUtility.HtmlEncode但没有成功,你能帮助我吗?
string sql = "insert into rss (title, description, link, pubdate) values (?,?,?, " +
" STR_TO_DATE(?, '%a, %d %b %Y %H:%i:%s GMT'));";
OdbcCommand command;
OdbcDataAdapter adpter = new OdbcDataAdapter();
connection.Open();
command = new OdbcCommand(sql, connection);
command.Parameters.AddWithValue("param1", System.Net.WebUtility.HtmlEncode(xmlTitle.InnerText.ToString()));
command.Parameters.AddWithValue("param2", System.Net.WebUtility.HtmlEncode(xmlDescription.InnerText.ToString()));
command.Parameters.AddWithValue("param3", System.Net.WebUtility.HtmlEncode(xmlLink.InnerText.ToString()));
command.Parameters.AddWithValue("param4", System.Net.WebUtility.HtmlEncode(xmlPubDate.InnerText.ToString()));
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
connection.Close();
Run Code Online (Sandbox Code Playgroud)
Dmy*_*ara 14
您可以使用本机.NET方法转义文本中的特殊字符.当然,只有5个特殊字符,并且5个Replace()调用可能会成功,但我确信必须有内置的东西.
转换"&"为的示例"&"
为了解决这个问题,我发现了一个隐藏在SecurityElement类内部的本机方法.是的,没错 - SecurityElement.Escape(string s)将转义你的字符串并使其安全.
这很重要,因为如果我们要将数据复制或写入Infopath Text字段,则需要首先将其转义为非实体字符"&".
要替换的无效XML字符
"<" to "<"
">" to ">"
"\"" to """
"'" to "'"
"&" to "&"
命名空间是"System.Security".参考:http://msdn2.microsoft.com/en-us/library/system.security.securityelement.escape(VS.80).aspx
其他选项是自定义代码
public static string EscapeXml( this string s )
{
string toxml = s;
if ( !string.IsNullOrEmpty( toxml ) )
{
// replace literal values with entities
toxml = toxml.Replace( "&", "&" );
toxml = toxml.Replace( "'", "'" );
toxml = toxml.Replace( "\"", """ );
toxml = toxml.Replace( ">", ">" );
toxml = toxml.Replace( "<", "<" );
}
return toxml;
}
public static string UnescapeXml( this string s )
{
string unxml = s;
if ( !string.IsNullOrEmpty( unxml ) )
{
// replace entities with literal values
unxml = unxml.Replace( "'", "'" );
unxml = unxml.Replace( """, "\"" );
unxml = unxml.Replace( ">", ">" );
unxml = unxml.Replace( "<", "<" );
unxml = unxml.Replace( "&", "&" );
}
return unxml;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31600 次 |
| 最近记录: |