gpt4 book ai didi

c# - 如何对 XML 中的特殊字符进行编码

转载 作者:可可西里 更新时间:2023-11-01 08:53:44 27 4
gpt4 key购买 nike

我的字符串 XML 包含一系列特殊字符:

&
egrave;
&
rsquo;
&
rsquo;
&
rsquo;
&
ldquo;
&
rdquo;
&
rsquo
&
agrave;
&
agrave;

我需要替换数据库中插入字符串中的这些特殊字符,我尝试使用 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();

最佳答案

您可以使用 native .NET 方法转义文本中的特殊字符。当然,只有大约 5 个特殊字符,调用 5 个 Replace() 可能就可以了,但我确信必须有一些内置的东西。

转换示例 "&""&"

让我松了一口气的是,我发现了一个 native 方法,它隐藏在 SecurityElement 类的内部。是的,没错 - SecurityElement.Escape(string s) 将转义您的字符串并使其成为 XML 安全的。

这很重要,因为如果我们将数据复制或写入 Infopath 文本字段,需要先将其转义为非实体字符,如 "&" .

要替换为无效的 XML 字符

"<" to "&lt;"

">" to "&gt;"

"\"" to "&quot;"

"'" to "&apos;"

"&" to "&amp;"

命名空间是“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( "&", "&amp;" );
toxml = toxml.Replace( "'", "&apos;" );
toxml = toxml.Replace( "\"", "&quot;" );
toxml = toxml.Replace( ">", "&gt;" );
toxml = toxml.Replace( "<", "&lt;" );
}
return toxml;
}

public static string UnescapeXml( this string s )
{
string unxml = s;
if ( !string.IsNullOrEmpty( unxml ) )
{
// replace entities with literal values
unxml = unxml.Replace( "&apos;", "'" );
unxml = unxml.Replace( "&quot;", "\"" );
unxml = unxml.Replace( "&gt;", ">" );
unxml = unxml.Replace( "&lt;", "<" );
unxml = unxml.Replace( "&amp;", "&" );
}
return unxml;
}

关于c# - 如何对 XML 中的特殊字符进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22906722/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com