HTMLAgility Pack - OuterHtml Read-only?

html-agility-pack

Question

Hey there, I am traversing all the links in my own code base, and changing them from <a href="x"> to <asp:HyperLink>'s for localization reasons. I'm using the HTMLAgilityPack for this (and other things) and I'd like to just change the OuterHtml object for the links I find..but it's read-only?

I'm new to the HAP, do I need to create a new node and delete the old one? Has anyone run into this?

Thanks!

Popular Answer

Why use the HTML Agility Pack if you're treating the whole document as a string. Instead look up tags and replace those then write back the document.

var doc = new HtmlDocument();
doc.LoadHtml(yourString); // or doc.Load(yourStream);

var links = doc.DocumentNode.Descendants("a");
foreach (var link in links)
{
    link.Parent.Replace(ConvertLink(link), link);
}
string newDocument = doc.DocumentNode.OuterHtml; // Or doc.Save();

And your ConvertLink would look like this:

public HtmlNode ConvertLink(HtmlNode aTag)
{
    var link = HtmlNode.Create("asp:HyperLink");
    link.Attributes.Add(...);
    return link;
}

(not compiled, so might need some tweaking).



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