如何用C#将'á'编码为'&#225'?(UTF8)

Llo*_*rti 0 c# xml encoding utf-8

我想写使用UTF-8编码的XML文件,以及原始字符串可以有无效字符像"A",所以,我需要这些无效字符更改为有效的.

我知道有一种编码方法可以采用例如字符á并将其转换为字符组á.

我试图用C#来实现这一点,但我没有成功.我正在使用Encoding.UTF8函数,但我只用sema字符结束(即:á)或'?' 字符.

所以,你知道用C#来实现这个角色变化的正确方法吗?

谢谢你的时间和帮助:)

LLORENS

Roh*_*hit 5

您可以使用任何一种方法.

以下是使用C#编码XML的4种方法:

  1. string.Replace()5次

这很丑,但它确实有效.请注意,Replace("&", "&")必须是第一个替换,所以我们不替换其他已经转义的&.

string xml = "<node>it's my \"node\" & i like it<node>";
encodedXml = xml.Replace("&","&amp;").Replace("<","&lt;").Replace(">","&gt;").Replace("\"", "&quot;").Replace("'", "&apos;");

// RESULT: &lt;node&gt;it&apos;s my &quot;node&quot; &amp; i like it&lt;node&gt;
Run Code Online (Sandbox Code Playgroud)
  1. System.Web.HttpUtility.HtmlEncode()

用于编码HTML,但HTML是XML的一种形式,因此我们也可以使用它.主要用于ASP.NET应用程序.请注意,HtmlEncode不编码撇号(').

string xml = "<node>it's my \"node\" & i like it<node>";
string encodedXml = HttpUtility.HtmlEncode(xml);

// RESULT: &lt;node&gt;it's my &quot;node&quot; &amp; i like it&lt;node&gt;
Run Code Online (Sandbox Code Playgroud)
  1. System.Security.SecurityElement.Escape()

在Windows窗体或控制台应用程序中,我使用此方法.如果没有别的东西它可以节省我,包括我的项目中的System.Web参考,它编码所有5个字符.

string xml = "<node>it's my \"node\" & i like it<node>";
string encodedXml = System.Security.SecurityElement.Escape(xml);

// RESULT: &lt;node&gt;it&apos;s my &quot;node&quot; &amp; i like it&lt;node&gt;
Run Code Online (Sandbox Code Playgroud)
  1. System.Xml.XmlTextWriter

使用XmlTextWriter,您不必担心转义任何内容,因为它会在需要的地方转义字符.例如,在属性中它不会转义撇号,而在节点值中它不会转义撇号和qoutes.

string xml = "<node>it's my \"node\" & i like it<node>";
using (XmlTextWriter xtw = new XmlTextWriter(@"c:\xmlTest.xml", Encoding.Unicode))
{

    xtw.WriteStartElement("xmlEncodeTest");
    xtw.WriteAttributeString("testAttribute", xml);
    xtw.WriteString(xml);
    xtw.WriteEndElement();

}

// RESULT:
/*
<xmlEncodeTest testAttribute="&lt;node&gt;it's my &quot;node&quot; &amp; i like it&lt;node&gt;">
    &lt;node&gt;it's my "node" &amp; i like it&lt;node&gt;
</xmlEncodeTest>
*/
Run Code Online (Sandbox Code Playgroud)

[ http://weblogs.sqlteam.com/mladenp/archive/2008/10/21/Different-ways-how-to-escape-an-XML-string-in-C.aspx]