Converting & to & etc

2019-02-02 19:29发布

问题:

I want to convert & to &, " to " etc. Is there a function in c# that could do that without writing all the options manually?

回答1:

System.Web.HttpUtility.HtmlDecode()

Edit: Note from here that "To encode or decode values outside of a web application, use..."

System.Net.WebUtility.HtmlDecode()


回答2:

Use the static method

HttpUtility.HtmlEncode

to change & to & and " to ". Use

HttpUtility.HtmlDecode

to do the reverse.



回答3:

You can use System.Net.WebUtility.HtmlDecode(uri);



回答4:

Server.HtmlDecode.



回答5:

A good article about this subject : Different ways how to escape an XML string in C#



回答6:

using System.Web; 
...
var html = "this is a sample & string"; 
var decodedhtml = HttpUtility.HtmlDecode(html);


回答7:

For .NET < 4 simple encoder

    public static string HtmlEncode(string value)
    {
        return value.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;");
    }