How to change all images src attributes using HTML Agility?

c# html html-agility-pack

Question

I need to convert all src attributes to point to the absolute path instead of relative path. I tried this using HTML Agility:

string html = "<body><div><img src=\"/folder/a.png\"/></div><div> <img src=\"/folder/b.png\"/></div></body>";
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
foreach (var node in htmlDoc.DocumentNode.SelectNodes("//img"))
{
   var src = node.Attributes[@"src"].Value;
   if (src.StartsWith("/"))
      node.SetAttributeValue("//src", "www.abc.xyz" + src);
}
var newHtml = htmlDoc.Text;

But src attributes still points to the relative path!

Accepted Answer

You have to use htmlDoc.DocumentNode.WriteTo() method to reflect your changes in your original html

string html = "<body><div><img src=\"/folder/a.png\"/></div><div> <img src=\"/folder/b.png\"/></div></body>";
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
foreach (var node in htmlDoc.DocumentNode.SelectNodes("//img"))
{
    var src = node.Attributes[@"src"].Value;
    if (src.StartsWith("/"))
        node.SetAttributeValue("src", "www.abc.xyz" + src);
}

var newHtml = htmlDoc.DocumentNode.WriteTo();

Output:

enter image description here

enter image description here

Try once may it help you



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why