Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HtmlAgilityPack HtmlDocument : How to update outer html?

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
}
like image 971
user3062349 Avatar asked Feb 14 '23 06:02

user3062349


1 Answers

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

var newNode = HtmlNode.CreateNode(strNewOuterHtml);
nestedtable.ParentNode.ReplaceChild(newNode, nestedtable);
like image 130
jessehouwing Avatar answered Feb 22 '23 22:02

jessehouwing