24

I'm looking for some function that will decode a good amount of HTML entities.

Reason is I am working on some code to take HTML content and turning it into plain text, the issue that I have is a lot of entities do not get converted using HttpUtility.HtmlDecode.

Some examples of entities I'm concerned about are  , &, ©.

This is for .net 3.5.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Matthew
  • 24,703
  • 9
  • 76
  • 110
  • 1
    I switched to .Net 3.5 and used `Console.WriteLine(HttpUtility.HtmlDecode(" , &, ©"));` and it worked fine for me. I can't figure out why you'd be having trouble. Do you have a weird string encoding or something? – John Gibb Dec 01 '11 at 22:30

2 Answers2

36

Then maybe you will need the HttpUtility.HtmlDecode?. It should work, you just need to add a reference to System.Web. At least this was the way in .Net Framework < 4.

For example the following code:

MessageBox.Show(HttpUtility.HtmlDecode("&amp;&copy;"));

Worked and the output was as expected (ampersand and copyright symbol). Are you sure the problem is within HtmlDecode and not something else?

UPDATE: Another class capable of doing the job, WebUtility (again HtmlDecode method) came in the newer versions of .Net. However, there seem to be some problems with it. See the HttpUtility vs. WebUtility question.

Community
  • 1
  • 1
Pavel Donchev
  • 1,809
  • 1
  • 17
  • 29
23

Use WebUtility.HtmlDecode included in .Net 4

For example, if I run in a console app:

  Console.WriteLine(WebUtility.HtmlDecode("&nbsp;, &amp;, &copy;"));

I get , &, c

John Gibb
  • 10,603
  • 2
  • 37
  • 48
  • 1
    I probably should have said this is for .net 3.5. I +1'ed you though. Thank you anyway. – Matthew Dec 01 '11 at 22:06
  • What is the difference between WebUtility and HttpUtility's `HtmlDecode` method? – crush May 28 '14 at 21:41
  • There's an answer here: http://stackoverflow.com/questions/17352981/webutility-htmldecode-vs-httputilty-htmldecode In short - WebUtility came with WinRT, it's newer while the HttpUtility is the old one (used all over the place so I expect it to stay). Also I think WebUtility is in System.dll (System.Net), which makes it a bit more accessible for WinApps (you don't have to depend on System.Web) if I remember correctly. – Pavel Donchev May 25 '15 at 05:15