Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating HTML Tags in a String in C#

Tags:

c#

.net

asp.net

Assume that we have the following HTML strings.

string A = " <table width=325><tr><td width=325>test</td></tr></table>"
string B = " <<table width=325><tr><td width=325>test</td></table>"

How can we validate A or B in C# according to HTML specifications?

A should return true whereas B should return false.

like image 614
Cas Sakal Avatar asked Sep 22 '11 18:09

Cas Sakal


1 Answers

For this specific case you can use HTML Agility Pack to assert if the HTML is well formed or if you have tags not opened.

var htmlDoc = new HtmlDocument();

htmlDoc.LoadHtml(
    "WAVEFORM</u> YES, <u>NEGATIVE AUSCULTATION OF EPIGASTRUM</u> YES,");

foreach (var error in htmlDoc.ParseErrors)
{
    // Prints: TagNotOpened
    Console.WriteLine(error.Code);
    // Prints: Start tag <u> was not found
    Console.WriteLine(error.Reason); 
}

Checking a HTML string for unopened tags

like image 124
sikender Avatar answered Oct 03 '22 08:10

sikender