如何在XML中编码特殊字符

时间:2014-04-07 08:01:12

标签: c# xml

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

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

我需要在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();

7 个答案:

答案 0 :(得分:12)

您可以使用本机.NET方法转义文本中的特殊字符。当然,只有5个特殊字符,5个Replace()调用可能会成功,但我确信必须有内置的东西。

"&"转换为"&"

的示例

为了解脱这个问题,我发现了一个隐藏在SecurityElement类内部的本机方法。是的,没错 - SecurityElement.Escape(string s)将转义你的字符串并使其安全。

这很重要,因为如果我们要将数据复制或写入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;
}

答案 1 :(得分:10)

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

答案 2 :(得分:4)

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

答案 3 :(得分:0)

Statement toxml = toxml.Replace( "&", "&amp;" );

这必须首先完成。否则,在调用此最后一个字符时,会将所有以前的“&”(“或”)替换为&s;

答案 4 :(得分:0)

简单代码:

    public static string ToXmlStr(string value) => String.IsNullOrEmpty(value) ? "" : value.Replace("&", "&amp;").Replace("'", "&apos;").Replace("\"", "&quot;").Replace(">", "&gt;").Replace("<", "&lt;");

    public static string FromXmlStr(string xmlStr) => String.IsNullOrEmpty(xmlStr) ? "" : xmlStr.Replace("&apos;", "'").Replace("&quot;", "\"").Replace("&gt;", ">").Replace("&lt;", "<").Replace("&amp;", "&");

    public static string ToMultilineXmlStr(string value) => String.IsNullOrEmpty(value) ? "" :
        value.Replace("\r", "").Split('\n').Aggregate(new StringBuilder(), (s, n) => s.Append("<p>").Append(ToXmlStr(n)).Append("</p>\n")).ToString();

请注意:对于xml中的多行值,通常无需将每行封装到<p> tag. So "<'&A'>\n<'&B'>" => "<p>&lt;&amp;A;&gt;</p><p>&lt;&amp;B;&gt;</p>"

答案 5 :(得分:0)

您可以使用 System.Xml.Linq.XElement 对 XML 中的特殊字符进行编码。

像这样:

var val = "test&<";
var node = new XElement("Node");
node.Value = val ?? node.Value;
Console.WriteLine(node.ToString());

输出:

<块引用>

"test&<"

答案 6 :(得分:-1)

还有3种方法可以通过您尝试的方法完成:

  1. 使用string.Replace()5次
  2. 使用System.Web.HttpUtility.HtmlEncode()
  3. System.Xml.XmlTextWriter

我可以解释每种情况,但我发现了this link to be mightily useful

相关问题