0 Comments

AngleSharp is a HTML parser library for .NET. Previously I’ve mainly used Html Agility Pack for parsing, but AngleSharp seems to be getting quite much traction nowadays.

I had a scenario where I wanted to use AngleSharp to wrap all the images with links. Given the following HTML:

<img src="2019-02-17-13-10-47.png" class="img-fluid" alt="Test stuff">

I wanted to transform it to this:

<a href="2019-02-17-13-10-47.png" class="lightbox">
	<img src="2019-02-17-13-10-47.png" class="img-fluid" alt="Test stuff">
</a>

Here’s how you can do this:

  1. Create the new link wrapper
  2. Get image’s original parent element
  3. Replace the image parent element’s image with the link wrapper
  4. Set image as the child of the wrapper

In C# using AngleSharp:

                var wrapperLink = document.CreateElement("a");
                wrapperLink.SetAttribute("href", image.GetAttribute("src"));
                wrapperLink.ClassName = "lightbox";

                var imageParent = image.ParentElement;
                imageParent.ReplaceChild(wrapperLink, image);
                wrapperLink.AppendChild(image);
Where document is of type IHtmlDocument and image is of type IHtmlImageElement.