将HTML代码转换为.NET字符串

时间:2010-08-27 18:31:53

标签: .net string

我有以下HTML代码:

<P>Notes:&nbsp;&nbsp; Mails: <BR> &nbsp; 1. <A href="mailto:example@mail.com">example@mail.com</A></P>

当然,当我尝试将其传递给字符串时,它会给我错误:

 string s =  "<P>Notes:&nbsp;&nbsp; Mails: <BR> &nbsp; 1. <A href="mailto:example@mail.com">example@mail.com</A></P>";

有没有办法可以将HTML转换为.NET等价物,最好不要改变格式?

提前感谢。

7 个答案:

答案 0 :(得分:3)

转义引号:

string s =  "<P>Notes:&nbsp;&nbsp; Mails: <BR> &nbsp; 1. <A href=\"mailto:example@mail.com\">example@mail.com</A></P>";

答案 1 :(得分:1)

看起来你只需要逃避引号:

 string s =  "<P>Notes:&nbsp;&nbsp; Mails: <BR> &nbsp; 1. <A href=\"mailto:example@mail.com\">example@mail.com</A></P>";

在C#中"表示字符串的开头或结尾,要在字符串中使用",您需要像\"一样“转义”它。您也可以使用格式为<{p>的verbatim string literals

string s = @"this is a string with "" <-- a quote inside";

答案 2 :(得分:0)

试试这个:

string s = "<P>Notes:&nbsp;&nbsp; Mails: <BR> &nbsp; 1. <A href='mailto:example@mail.com'>example@mail.com</A></P>";

如果不转义它们,则不能在字符串中使用双引号。或者使用我发布的版本。

答案 3 :(得分:0)

string s =  "<P>Notes:&nbsp;&nbsp; Mails: <BR> &nbsp; 1. <A href=\"mailto:example@mail.com\">example@mail.com</A></P>";

你必须用斜杠“\”来转义引号。

答案 4 :(得分:0)

C#中没有字符串文字,你不必转义双引号。

var str1 = "<A href=\"mailto:example@mail.com\">";
var str2 = @"<A href=""mailto:example@mail.com"">";

答案 5 :(得分:0)

string s = "<P>Notes:&nbsp;&nbsp;Mails:<br />&nbsp;1.<A href=\"mailto:example@mail.com\">example@mail.com</A></P>";

答案 6 :(得分:0)

您有几种选择:

对于编译时支持,你可以使用\"来转义引号,正如其他人多次证明的那样(所以我不再重复),你可以使用文字字符串@"..."来逃避使用""引用,或者您可以将字符串粘贴到资源文件中,让Visual Studio为您处理转义。

或者,如果您替换单个双引号,您通常可以顺利通过;但是,如果你的字符串包含JavaScript,这有时会成为一个问题,因为手头有两种类型的引号可能是必要的恶意。

在运行时,您可以通过从文件,数据库或其他资源中读取文本来避免转义;但是,我觉得这不是你的意图。