将HTML标记转换为实体参考时,字符文字中的字符过多 [英] Too many characters in character literal while converting HTML Tag to Entity reference

查看:60
本文介绍了将HTML标记转换为实体参考时,字符文字中的字符过多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过C#代码生成了HTML标记.我能够在文本区域中正确呈现.当我用Google搜索它时,我发现了.要在文本区域中呈现HTML标签,我们需要将'<','>'转换为HTML实体引用.但是,当我尝试使用 String.Replace 进行替换时,它会引发错误:字符文字中的字符过多

I have generated an HTML tag through C# code. I am able to render correctly in the text area. When I googled it, I found this. To render the HTML tags in the text area, we need to convert the '<','>' into HTML entity references. But when I am trying to replace using String.Replace, it throws an error: Too many characters in character literal .

string psHtmlOutput="<html><body><table border='0' cellspacing='3' cellpadding='3'><tr><th> Name </th><th>DomainName</th><th>DomainType</th><th>Defualt</th></tr><tr><td>india.local</td><td>india.local</td><td>Authoritative</td><td>True</td></tr></table></body></html>";

psHtmlOutput.Replace('>','&gt;');
psHtmlOutput.Replace('<','&lt;');

错误:字符文字中的字符过多

Error: Too many characters in character literal

请帮助;我该怎么办?

推荐答案

String.Replace 方法有两个重载:

  1. 一个对 String s进行操作的人.
  2. 一个可对 Char s进行操作的对象.
  1. One that operates on Strings.
  2. One that operates on Chars.

在C#中,单引号用于指定 Char 文字.因为使用了单引号,所以使用了方法的第二个重载.但是,您的第二个参数不是有效的字符文字,因为 & gt; 不是单个字符.

In C#, single quotation marks are used to specify Char literals. Because you have used single quotes, the second overload of the method has been used. However, your second argument is not a valid character literal because &gt; is not a single character.

因此,如果您实际上想用字符串替换字符,只需使用带字符串的重载:

So if you actually want to replace the character with a string, just use the overload that takes strings:

psHtmlOutput.Replace(">", "&gt;");
psHtmlOutput.Replace("<", "&lt;");

这篇关于将HTML标记转换为实体参考时,字符文字中的字符过多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆