如何将货币符号转换为相应的 HTML 实体

How to convert currency symbol to corresponding HTML entity

System.Net.WebUtility.HtmlDecode("€"); // returns €
System.Net.WebUtility.HtmlEncode("€"); // also returns €

如何将 €(或任何其他货币符号)转换为相应的 html 实体。

在这个例子中€ => €

我正在使用 .Net 4.6.1

HtmlEncodeHtmlDecode 不对称。

HtmlEncode 只会编码少数特殊字符:

  • < => &lt;
  • > => &gt;
  • & => &amp;
  • ' => &#39;
  • " => &quot;

对于一些 unicode 字符,它会将它们转换为 &#<num>; 格式。

因此不会发生到 HtmlEntities 的转换。

HtmlEncode 只查找一些特殊字符并将它们替换为硬编码值,另外还有一些更高的 ASCII 字符 (160 - 255),如 here. The only way to encode into entity names is by specifying them manually. I gave it a shot and built a wrapper around the System.Net.WebUtility class while leveraging the existing Html entities dataset used by .NET to decode as well so that decoding continues to work with this solution. I've hosted it on github: WebUtilityWrapper 所述。您可以如下所示使用它:

WebUtilityWrapper.HtmlEncode("€"); // Returns &euro;
WebUtilityWrapper.HtmlEncode("Δ"); // Returns &Delta;
WebUtilityWrapper.HtmlEncode("&"); // Returns &amp;
WebUtilityWrapper.HtmlEncode("$"); // Returns $ 
WebUtilityWrapper.HtmlEncode("€¢£¥"); // Returns &euro;&cent;&pound;&yen;

我已经通过编码和解码来测试它,然后验证我们是否获得了大量 unicode 字符的原始字符串。分享更多测试:

HtmlEncode() 响应使用框架的 HtmlEncode: (link)

// Alphabets
$+0123456789&lt;=&gt;ABCDEFGHIJKLMNOPQRSTUVWXYZ^`abcdefghijklmnopqrstuvwxyz|~

// Unicode 162 to 254
&#162;&#163;&#164;&#165;&#166;&#167;&#168;&#169;&#170;&#172;&#174;&#175;&#176;
&#177;&#180;&#181;&#182;&#184;&#186;&#192;&#193;&#194;&#195;&#196;&#197;&#198;
&#199;&#200;&#201;&#202;&#203;&#204;&#205;&#206;&#207;&#208;&#209;&#210;&#211;
&#212;&#213;&#214;&#215;&#216;&#217;&#218;&#219;&#220;&#221;&#222;&#223;&#224;
&#225;&#226;&#227;&#228;&#229;&#230;&#231;&#232;&#233;&#234;&#235;&#236;&#237;
&#238;&#239;&#240;&#241;&#242;&#243;&#244;&#245;&#246;&#247;&#248;&#249;&#250;
&#251;&#252;&#253;&#254;

// Unicodes for Greek Alphabet
ΑΒΓΔΕΖΗΘΙΚΛΜΝ

// Unicodes for 9824 - 9830
♠♣♥♦

HtmlEncode() 响应使用 WebUtilityWrapper.HtmlEncode:

// Alphabets
$+0123456789&lt;=&gt;ABCDEFGHIJKLMNOPQRSTUVWXYZ^`abcdefghijklmnopqrstuvwxyz|~

// Unicode 162 to 254
&cent;&pound;&curren;&yen;&brvbar;&sect;&uml;&copy;&ordf;&not;&reg;&macr;&deg;
&plusmn;&acute;&micro;&para;&cedil;&ordm;&Agrave;&Aacute;&Acirc;&Atilde;&Auml;&Aring;&AElig;
&Ccedil;&Egrave;&Eacute;&Ecirc;&Euml;&Igrave;&Iacute;&Icirc;&Iuml;&ETH;&Ntilde;&Ograve;&Oacute;
&Ocirc;&Otilde;&Ouml;&times;&Oslash;&Ugrave;&Uacute;&Ucirc;&Uuml;&Yacute;&THORN;&szlig;&agrave;
&aacute;&acirc;&atilde;&auml;&aring;&aelig;&ccedil;&egrave;&eacute;&ecirc;&euml;&igrave;&iacute;
&icirc;&iuml;&eth;&ntilde;&ograve;&oacute;&ocirc;&otilde;&ouml;&divide;&oslash;&ugrave;&uacute;
&ucirc;&uuml;&yacute;&thorn;

// Unicodes for Greek alphabet
&Alpha;&Beta;&Gamma;&Delta;&Epsilon;&Zeta;&Eta;&Theta;&Iota;&Kappa;&Lambda;&Mu;&Nu;
&Xi;&Omicron;&Pi;&Rho;&Sigma;&Tau;&Upsilon;&Phi;&Chi;&Psi;&Omega;

// Unicodes for 9824 - 9830
&spades;&clubs;&hearts;&diams;

希望对您有所帮助!