HtmlAgilityPack replace node

Viewed 27819

I want to replace a node with a new node. How can I get the exact position of the node and do a complete replace?

I've tried the following, but I can't figured out how to get the index of the node or which parent node to call ReplaceChild() on.

string html = "<b>bold_one</b><strong>strong</strong><b>bold_two</b>";
HtmlDocument document = new HtmlDocument();
document.LoadHtml(html);

var bolds = document.DocumentNode.Descendants().Where(item => item.Name == "b");

foreach (var item in bolds)
{

    string newNodeHtml = GenerateNewNodeHtml();
    HtmlNode newNode = new HtmlNode(HtmlNodeType.Text, document, ?);
    item.ParentNode.ReplaceChild( )
}
2 Answers

Have Implemented the following solution to achieve the same.

var htmlStr = "<b>bold_one</b><div class='LatestLayout'><div class='olddiv'><strong>strong</strong></div></div><b>bold_two</b>";
var htmlDoc = new HtmlDocument();
    HtmlDocument document = new HtmlDocument();
    document.Load(htmlStr);

htmlDoc.DocumentNode.SelectSingleNode("//div[@class='olddiv']").Remove();
htmlDoc.DocumentNode.SelectSingleNode("//div[@class='LatestLayout']").PrependChild(newChild)

htmlDoc.Save(FilePath); // FilePath .html file with full path if need to save file.

so selecting an object and removing respective HTML object

and appending it as chile. of respective object.

Related