I want to add a link to every image in the HTML with the value of the "href" attribute be the "src" attribute of the image. Namely changing the
"<p> <img src="test.jpg"/></p>"
to
<p><a href="test.jpg"><img src="jpg"/></a></p>
And my code coming:
using HtmlAgilityPack;
var imgs = document.DocumentNode.Descendants("img");
foreach (HtmlNode node in imgs)
{
if (node.ParentNode.Name != "a")
{
string replaceStr = string.Format("<a href=\"{0}\">{1}</a>", node.GetAttributeValue("src", null), node.OuterHtml);
//node.OuterHtml= replaceStr; It doesn't work, the outerHtml is readonly
//node.ParentNode.RemoveChild(node, true);
}
}
So how should I modify my code to make it work?
Updated: after updating my code:
var imgs = document.DocumentNode.Descendants("img");
foreach (var node in imgs)
{
if (node.ParentNode.Name != "a")
{
var a = document.CreateElement("a");
a.SetAttributeValue("href", node.GetAttributeValue("src", null));
a.ChildNodes.Add(node);
node.ParentNode.ReplaceChild(a, node);
}
}
An error shows up "Unhandled InvalidOperationException ".