【问题标题】:Decode HTML entities [duplicate]解码 HTML 实体 [重复]
【发布时间】:2014-01-15 08:14:37
【问题描述】:

我有一个像 Fee&#108 这样的字符串,我想将它解码为它的 ascii 表示形式 - feel
是否有 C# 中的任何库可以做到这一点,还是我必须手动完成?

【问题讨论】:

  • 你真的想要 ASCII 吗?还是您想要一个 .NET/C# 字符串(即 UTF-8)?
  • @elgonzo UTF-8 就可以了。
  • 我不确定这到底有什么限制,但您可以(可能)尝试 HtmlDecode:msdn.microsoft.com/en-us/library/7c5fyk1k.aspx
  • 使用WebUtility.HtmlDecode 可能比使用HttpUtility.HtmlDecode 更好。见here for explanation
  • @elgonzo .NET 字符串不是 UTF-8,而是 UTF-16。

标签: c# html-entities


【解决方案1】:

要解码字符串,请使用WebUtility.HtmlDecode

这是一个示例LINQPad 程序,演示:

void Main()
{
    string s = "Feel";
    string decoded = WebUtility.HtmlDecode(s);
    decoded.Dump();
}

输出:

Feel

注意:您在问题中提供的字符串中缺少分号。没有最后的分号,输出将是:

Fee&#108

【讨论】:

    【解决方案2】:

    您可以使用以下代码,这是一个控制台示例:

    using System;
    using System.Text;
    using System.Text.RegularExpressions;
    
    namespace ConsoleApplication
    {
        class Program
        {
            public static String ReplaceASCIICodesWithUTF(String target)
            {
                Regex codeSequence = new Regex(@"&#[0-9]{1,3};");
                MatchCollection matches = codeSequence.Matches(target);
                StringBuilder resultStringBuilder = new StringBuilder(target);
                foreach (Match match in matches)
                {
                    String matchedCodeExpression = match.Value;
                    String matchedCode = matchedCodeExpression.Substring(2, matchedCodeExpression.Length - 3);
                    Byte resultCode = Byte.Parse(matchedCode);
                    resultStringBuilder.Replace(matchedCodeExpression, ((Char)resultCode).ToString());
                }
                return resultStringBuilder.ToString();
            }
    
            static void Main(string[] args)
            {
                String rawData = "Feel";
                Console.WriteLine(ReplaceASCIICodesWithUTF(rawData));
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      解码:

      HttpUtility.HtmlDecode

      然后,例如,

      ASCIIEncoding

      GetBytes/GetString(在解码后的字符串中获取字节,然后从这些字节中获取字符串)

      【讨论】:

        猜你喜欢
        • 2011-08-13
        • 2012-05-29
        • 1970-01-01
        • 2013-03-20
        • 1970-01-01
        • 2016-08-13
        相关资源
        最近更新 更多