HtmlAgilityPack HtmlDocument : How to update outer html?

c# html-agility-pack xmldocument

Question

I am trying to update the Outer Html using HtmlAgilityPack. The property shows as read-only. My question is how to update the Outer Html? Note: I do have a need for updating the outer html (not only the inner html). Here is the code:

// Check if there is a nested table
HtmlAgilityPack.HtmlNode nestedtable = tr.SelectSingleNode(".//table");
if (nestedtable != null)
{
    // Save Inner/Outer Html and update Outer Html
    string strInnerHtml = nestedtable.InnerHtml;
    string strOuterHtml = nestedtable.OuterHtml;
    string strNewOuterHtml = "<table><tr><td><table><tr><td>inner1update</td><td>inner2update</td></tr></table></td></tr></table>";

    // Now update source HtmlDocument
    nestedtable.OuterHtml = strNewOuterHtml;  
    // ^^^ Error line: Property or indexer  
    //HtmlAgilityPack.HtmlNode.OuterHtml' cannot be assigned to -- it is read only
}

Popular Answer

You can use ReplaceChild on the parent, the syntax looks like this

var newNode = HtmlNode.CreateNode(strNewOuterHtml);
nestedtable.ParentNode.ReplaceChild(newNode, nestedtable);



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