如何在XML中编码特殊字符

Ham*_*lis 10 c# xml

我的字符串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 "&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;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果使用@DmytroKhmara的自定义代码,则必须先将`toxml = toxml.Replace(“&”,“&amp;”);`替换为`EscapeXML`。否则,您将在所有其他转义的字符中都跳过与号。 (3认同)

Dal*_*las 10

你可以使用HttpUtility.HtmlDecode或.NET 4.0+你也可以使用WebUtility.HtmlDecode


BRA*_*mel 6

而不是System.Net.WebUtility.HtmlEncode你必须使用System.Net.WebUtility.HtmlDecode