delete children from html agility pack

c# html-agility-pack


I'm having difficulty trying to remove a div with a particular ID, and its children using the HTML Agility pack. I am sure I'm just missing a config option, but its Friday and I'm struggling.

The simplified HTML runs:

<html><head></head><body><div id='wrapper'><div id='functionBar'><div id='search'></div></div></div></body></html>

This is as far as I have got. The error thrown by the agility pack shows it cannot find a div structure:

<div id='functionBar'></div>

Here's the code so far (taken from Stackoverflow....)

HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
        // There are various options, set as needed
        //htmlDoc.OptionFixNestedTags = true;

        // filePath is a path to a file containing the html

        string output = string.Empty;

        // ParseErrors is an ArrayList containing any errors from the Load statement
        if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count > 0)
            // Handle any parse errors as required


            if (htmlDoc.DocumentNode != null)
               HtmlAgilityPack.HtmlNode bodyNode  = htmlDoc.DocumentNode.SelectSingleNode("//body");

                if (bodyNode != null)
                    HtmlAgilityPack.HtmlNode functionBarNode = bodyNode.SelectSingleNode ("//div[@id='functionBar']");


                    output = bodyNode.InnerHtml;
9/18/2009 2:28:17 PM

Accepted Answer


But functionBarNode is not a child of bodyNode.

How about functionBarNode.ParentNode.RemoveChild(functionBarNode, false)? (And forget the bit about finding bodyNode.)

10/19/2013 8:10:39 PM

Popular Answer

You can simply call:

var documentNode = document.DocumentNode;
var functionBarNode = documentNode.SelectSingleNode("//div[@id='functionBar']");

It is much simpler, and does the same as:

functionBarNode.ParentNode.RemoveChild(functionBarNode, false);

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow