views:

634

answers:

1

Hi,

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
        htmlDoc.LoadHtml(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

        }
        else
        {

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

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

                    bodyNode.RemoveChild(functionBarNode,false);

                    output = bodyNode.InnerHtml;
                }
            }
        }
A: 

bodyNode.RemoveChild(functionBarNode,false);

But functionBarNode is not a child of bodyNode.

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

bobince
genius - thank you!
Bob