HtmlAgilityPack HtmlDocument:如何更新外部html?

时间:2013-12-30 21:09:28

标签: c# html-agility-pack xmldocument

我正在尝试使用HtmlAgilityPack更新外部Html。该属性显示为只读。我的问题是如何更新外部Html?注意:我确实需要更新外部html(不仅仅是内部html)。这是代码:

// 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
}

1 个答案:

答案 0 :(得分:5)

您可以在父级上使用ReplaceChild,语法如下所示

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