将字符实体转换为其unicode等效项

Dan*_*Dan 12 .net html c# character-encoding

我在数据库中有html编码的字符串,但许多字符实体不仅仅是标准&<.像“和的实体—.不幸的是,我们需要将这些数据提供给基于闪存的rss阅读器,而flash不会读取这些实体,但它们会读取等效的unicode(ex “).

使用.Net 4.0,是否有任何实用方法可以将html编码的字符串转换为使用unicode编码的字符实体?

这是我需要的更好的例子.db有html字符串,如下所示:<p>John &amp; Sarah went to see $ldquo;Scream 4$rdquo;.</p>我需要在rss/xml文档中输出的内容<description>是:&lt;p&gt;John &amp;#38; Sarah went to see &amp;#8220;Scream 4&amp;#8221;.&lt;/p&gt;

我正在使用XmlTextWriter从数据库记录创建xml文档,类似于此示例代码http://www.dotnettutorials.com/tutorials/advanced/rss-feed-asp-net-csharp.aspx

所以我需要将数据库中的html字符串中的所有字符实体替换为unicode等效,因为基于flash的rss阅读器无法识别最常见的任何实体&amp;.

Tha*_*hew 7

我的第一个想法是,您的RSS阅读器能否接受实际角色?如果是这样,您可以使用HtmlDecode并直接输入.

如果确实需要将其转换为数字表示,则可以解析每个实体,HtmlDecode然后将其转换为a int以获取base-10 unicode值.然后将其重新插入字符串中.

编辑: 这里有一些代码来证明我的意思(它是未经测试的,但是得到了想法):

string input = "Something with &mdash; or other character entities.";
StringBuilder output = new StringBuilder(input.Length);

for (int i = 0; i < input.Length; i++)
{
    if (input[i] == '&')
    {
        int startOfEntity = i; // just for easier reading
        int endOfEntity = input.IndexOf(';', startOfEntity);
        string entity = input.Substring(startOfEntity, endOfEntity - startOfEntity);
        int unicodeNumber = (int)(HttpUtility.HtmlDecode(entity)[0]);
        output.Append("&#" + unicodeNumber + ";");
        i = endOfEntity; // continue parsing after the end of the entity
    }
    else
        output.Append(input[i]);
}
Run Code Online (Sandbox Code Playgroud)

我可能在那里的某个地方有一个错误的错误,但它应该是接近的.


Red*_*ins 5

HttpUtility.HtmlDecode对你有用吗?

我意识到它不会转换为 unicode 等效实体,而是将其转换为 unicode。您想要 unicode 等效实体有什么具体原因吗?

更新编辑


        string test = "<p>John &amp; Sarah went to see &ldquo;Scream 4&rdquo;.</p>";
        string decode = HttpUtility.HtmlDecode(test);
        string encode = HttpUtility.HtmlEncode(decode);

        StringBuilder builder = new StringBuilder();
        foreach (char c in encode)
        {
            if ((int)c > 127)
            {
                builder.Append("&#");
                builder.Append((int)c);
                builder.Append(";");
            }
            else
            {
                builder.Append(c);
            }
        }
        string result = builder.ToString();
Run Code Online (Sandbox Code Playgroud)