Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding all HTML Entities

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.

like image 384
Matthew Avatar asked Dec 01 '11 21:12

Matthew


People also ask

What is HTML entity decode?

HTML encoding converts characters that are not allowed in HTML into character-entity equivalents; HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters < and > are encoded as &lt; and &gt; for HTTP transmission.

How do you decode HTML tags?

HTML character decoding is the opposite process of encoding. The encoded characters are converted back to their original form in the decoding process. It decodes a string that contains HTML numeric character references and returns the decoded string. You can also choose to convert HTML code into JavaScript string.

Which method is used to decode the currently encoded HTML code?

The input string is encoded using the HtmlEncode method. The encoded string obtained is then decoded using the HtmlDecode method.

How do you show entities in HTML?

You have to use HTML character entities &lt; and &gt; in place of the < and > symbols so they aren't interpreted as HTML tags.


2 Answers

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.

like image 88
Pavel Donchev Avatar answered Sep 19 '22 06:09

Pavel Donchev


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

like image 38
John Gibb Avatar answered Sep 18 '22 06:09

John Gibb