7

I am attempting to replace this god awful collection of regular expressions that is currently used to clean up blocks of poorly formed HTML and stumbled upon the HTML Agility Pack for C#. It looks very powerful but yet, I couldn't find an example of how I want to use the pack which, in my mind, would be a desired functionality included in it. I am sure I am an idiot and cannot find a suitable method in the documentation.

Let me explain... say I had the following html:

<p class="someclass">
    <font size="3">
        <font face="Times New Roman">
            this is some text
            <a href="somepage.html">Some link</a>
        </font>
    </font>
</p>

... that I want to look like:

<p>
    this is some text
    <a href="somepage.html">Some link</a>
</p>

When I utilize the HtmlNode.Remove() method it removes the node plus all it's children. Is there a way to remove the node preserving the children?

3 Answers 3

6

On HtmlNode, the method RemoveChild has this overload:

public HtmlNode RemoveChild(HtmlNode oldChild, bool keepGrandChildren);

So this is how you would do it:

HtmlDocument doc = new HtmlDocument();
doc.Load("yourfile.htm");

foreach (HtmlNode font in doc.DocumentNode.SelectNodes("//font"))
{
    font.ParentNode.RemoveChild(font, true);
}

EDIT: It looks like the Replace w/ keepGrandChildren option is not working as expected, so here is an alternate implementation:

public static HtmlNode RemoveChild(HtmlNode parent, HtmlNode oldChild, bool keepGrandChildren)
{
    if (oldChild == null)
        throw new ArgumentNullException("oldChild");

    if (oldChild.HasChildNodes && keepGrandChildren)
    {
        HtmlNode prev = oldChild.PreviousSibling;
        List<HtmlNode> nodes = new List<HtmlNode>(oldChild.ChildNodes.Cast<HtmlNode>());
        nodes.Sort(new StreamPositionComparer());
        foreach (HtmlNode grandchild in nodes)
        {
            parent.InsertAfter(grandchild, prev);
        }
    }
    parent.RemoveChild(oldChild);
    return oldChild;
}

// this helper class allows to sort nodes using their position in the file.
private class StreamPositionComparer : IComparer<HtmlNode>
{
    int IComparer<HtmlNode>.Compare(HtmlNode x, HtmlNode y)
    {
        return y.StreamPosition.CompareTo(x.StreamPosition);
    }
}
4
  • This looks promising with one problem. It reverses the order of the grandchildren from the original.
    – nokturnal
    Commented Mar 21, 2011 at 13:22
  • @nokturnal - good catch! hhmmm. looks like a bug to me. I have updated my answer. Commented Mar 21, 2011 at 13:43
  • This looks like the right answer, but there are some flaws in the HTML Agility Pack with is probably going to lead me away from it for this project.
    – nokturnal
    Commented Apr 4, 2011 at 13:42
  • The first solution (before the EDIT) seems to work fine for me. Commented Jun 16, 2015 at 23:56
2

You could try using AngleSharp instead.

var parser = new HtmlParser();
var document = parser.Parse(html);

using (var writer = new StringWriter())
{
    document.ToHtml(writer, new PrettyMarkupFormatter());
    return writer.ToString();
}
2
  • 1
    Totally an amazing lib (as was it's pseudo-predecessor csquery), and I would totally recommend this now... it just didn't exist in 2011 :)
    – nokturnal
    Commented Jan 18, 2018 at 13:00
  • 1
    Currently, instead of parser.Parse you should use parser.ParseDocument.
    – Uwe Keim
    Commented Oct 23, 2019 at 8:34
-1

Once you find the

element use the InnerText method to get the text, Then do the remove and then insert the text.

1
  • Sorry, I guess my HTML examples were too simplistic. It needs to copy more than the InnerText to the parent element. Please see my revised / edited examples.
    – nokturnal
    Commented Mar 21, 2011 at 2:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.