Skip to content

Instantly share code, notes, and snippets.

@smdooley
Last active January 11, 2023 10:55
Show Gist options
  • Save smdooley/b7064d5ef11979d0df4cafab2913193e to your computer and use it in GitHub Desktop.
Save smdooley/b7064d5ef11979d0df4cafab2913193e to your computer and use it in GitHub Desktop.
Helper class to dynamically update table HTML markup
using HtmlAgilityPack;
namespace Concept.Core.Helpers
{
public static class TableMarkupHelper
{
public static ApplyHtmlStyleGuidelines(string text)
{
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(text);
ApplyTableHtml(htmlDocument);
return htmlDocument.DocumentNode.OuterHtml;
}
private static void ApplyTableHtml(HtmlDocument htmlDocument)
{
var elements = htmlDocumeht.DocumentNode.SelectNode("//table");
if(elements is null) return;
foreach(HtmlNode element in elements)
{
HtmlNode parent = element.ParentNode;
element.Attributes.Remove("border");
var headCells = element.SelectNodes("//th");
if(headCells is not null)
{
foreach(HtmlNode headCell in headCells)
{
headCell.Attributes.Remove("width");
headCell.Attributes.Remove("style");
var scope = headCell.GetAttributeValue("scope", "").Trim().ToLower();
switch(scope)
{
case "col":
case "colgroup":
headCell.Attributes.Append("role", "columnheader");
break;
case "row":
case "rowgroup":
headCell.Attributes.Append("role", "rowheader");
break;
default:
headCell.Attributes.Append("role", "cell");
break;
}
headCell.Attributes.Append("aria-label", headCell.InnerText.Trim());
}
}
var bodyCells = element.SelectNodes("//td");
if(bodyCells is not null)
{
foreach(HtmlNode bodyCell in bodyCells)
{
bodyCell.Attributes.Remove("width");
bodyCell.Attributes.Remove("style");
bodyCell.Attributes.Append("role", "cell");
}
}
HtmlDocument wrapperDocument = new HtmlDocument();
HtmlNode wrapperElement = wrapperDocument.CreateElement("div");
wrapperElement.AddClass("table_product_summary");
wrapperElement.SetAttributeValue("style", "overflow-x: auto;");
wrapperElement.Appendachild(element);
parent.ReplaceChild(wrapperElement, element);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment