Skip to content

Instantly share code, notes, and snippets.

@garpunkal
Created January 3, 2020 16:39
Show Gist options
  • Save garpunkal/1e6df931cbf6849489d365886f89f4c8 to your computer and use it in GitHub Desktop.
Save garpunkal/1e6df931cbf6849489d365886f89f4c8 to your computer and use it in GitHub Desktop.
HtmlStringExtensions.cs
public static class HtmlStringExtensions
{
public static bool IsNullOrWhiteSpace(this IHtmlString htmlString)
{
return htmlString == null || string.IsNullOrWhiteSpace(htmlString.ToHtmlString());
}
public static HtmlString AddClass(this IHtmlString html, string css)
{
return html.UpdateElement(node => node.AddClass(css));
}
public static HtmlString AddClassToOuterParagraphTag(this IHtmlString html, string css)
{
return html.UpdateElement("//p", node => node.AddClass(css));
}
public static HtmlString RemoveOuterParagraphTag(this IHtmlString html)
{
var doc = GetHtmlDocument(html);
var node = doc?.DocumentNode.ChildNodes?.FirstOrDefault(n => n.NodeType != HtmlNodeType.Text);
return new HtmlString(node?.InnerHtml.Trim());
}
public static HtmlString UpdateElement(this IHtmlString html, Action<HtmlNode> updateFunc)
{
var doc = GetHtmlDocument(html);
var node = doc?.DocumentNode.ChildNodes?.FirstOrDefault(n => n.NodeType != HtmlNodeType.Text);
if (node != null)
updateFunc(node);
return new HtmlString(doc?.DocumentNode.OuterHtml);
}
public static HtmlString UpdateElement(this IHtmlString html, string tagPath, Action<HtmlNode> updateFunc)
{
var doc = GetHtmlDocument(html);
var node = doc?.DocumentNode.SelectSingleNode(tagPath);
updateFunc(node);
return new HtmlString(doc?.DocumentNode.OuterHtml);
}
private static HtmlDocument GetHtmlDocument(IHtmlString html)
{
var content = html.ToString();
if (content.IsNullOrWhiteSpace())
return null;
var doc = new HtmlDocument();
doc.LoadHtml(content);
return doc;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment