51

I've seen a few related questions out here, but they don’t exactly talk about the same problem I am facing.

I want to use the HTML Agility Pack to remove unwanted tags from my HTML without losing the content within the tags.

So for instance, in my scenario, I would like to preserve the tags "b", "i" and "u".

And for an input like:

<p>my paragraph <div>and my <b>div</b></div> are <i>italic</i> and <b>bold</b></p>

The resulting HTML should be:

my paragraph and my <b>div</b> are <i>italic</i> and <b>bold</b>

I tried using HtmlNode's Remove method, but it removes my content too. Any suggestions?

3

5 Answers 5

65

I wrote an algorithm based on Oded's suggestions. Here it is. Works like a charm.

It removes all tags except strong, em, u and raw text nodes.

internal static string RemoveUnwantedTags(string data)
{
    if(string.IsNullOrEmpty(data)) return string.Empty;

    var document = new HtmlDocument();
    document.LoadHtml(data);

    var acceptableTags = new String[] { "strong", "em", "u"};

    var nodes = new Queue<HtmlNode>(document.DocumentNode.SelectNodes("./*|./text()"));
    while(nodes.Count > 0)
    {
        var node = nodes.Dequeue();
        var parentNode = node.ParentNode;

        if(!acceptableTags.Contains(node.Name) && node.Name != "#text")
        {
            var childNodes = node.SelectNodes("./*|./text()");

            if (childNodes != null)
            {
                foreach (var child in childNodes)
                {
                    nodes.Enqueue(child);
                    parentNode.InsertBefore(child, node);
                }
            }

            parentNode.RemoveChild(node);

        }
    }

    return document.DocumentNode.InnerHtml;
}
5
  • 1
    Thanks for this solution! But please note that it doesn't remove unacceptable tags nested inside of an acceptable one--if, for example, you allow "P" but don't allow "SPAN", the span won't be removed. I fixed this by running this method recursively, splitting from "var nodes..." down into a separate method that calls itself on any "node" var that is in the acceptable list and has child nodes.
    – Sean Mahan
    Jul 20, 2016 at 3:00
  • Great @SeanMahan. Feel free to edit my post with your solution - I trust that it is much better :) Jul 21, 2016 at 11:10
  • @SeanMahan Please do! I would like to see your solution.
    – StarQuake
    May 11, 2017 at 13:49
  • Doesn't work for input: '10 > 7 <b>but</b> 10 < 30' It gives: '10 > 7 but 10 ' Oct 3, 2017 at 13:09
  • 8
    But that is also very invalid HTML. Oct 3, 2017 at 16:23
17

How to recursively remove a given list of unwanted html tags from an html string

I took @mathias answer and improved his extension method so that you can supply a list of tags to exclude as a List<string> (e.g. {"a","p","hr"}). I also fixed the logic so that it works recursively properly:

public static string RemoveUnwantedHtmlTags(this string html, List<string> unwantedTags)
    {
        if (String.IsNullOrEmpty(html))
        {
            return html;
        }

        var document = new HtmlDocument();
        document.LoadHtml(html);

        HtmlNodeCollection tryGetNodes = document.DocumentNode.SelectNodes("./*|./text()");

        if (tryGetNodes == null || !tryGetNodes.Any())
        {
            return html;
        }

        var nodes = new Queue<HtmlNode>(tryGetNodes);

        while (nodes.Count > 0)
        {
            var node = nodes.Dequeue();
            var parentNode = node.ParentNode;

            var childNodes = node.SelectNodes("./*|./text()");

            if (childNodes != null)
            {
                foreach (var child in childNodes)
                {
                    nodes.Enqueue(child);                       
                }
            }

            if (unwantedTags.Any(tag => tag == node.Name))
            {               
                if (childNodes != null)
                {
                    foreach (var child in childNodes)
                    {
                        parentNode.InsertBefore(child, node);
                    }
                }

                parentNode.RemoveChild(node);

            }
        }

        return document.DocumentNode.InnerHtml;
    }
4
  • 1
    Note: If I'm reading this correctly this function removes a list of unwantedTags and the function posted by @mathias keeps acceptableTags. Which is quite different.
    – StarQuake
    May 11, 2017 at 13:59
  • @StarQuake It's an answer to the original question, which is to remove unwanted tags. I just adapted Mathias' code to make it more flexible.
    – theyetiman
    May 15, 2017 at 8:35
  • 1
    The original question asks how to remove unwanted tags by supplying allowedTags. The title of the original question is misleading. The example given also illustrates a function that leaves allowedTags in, instead of removing disallowed tags.
    – StarQuake
    May 15, 2017 at 13:27
  • 1
    @StarQuake The question does not mention anything about the implementation requiring an "allowedTags" list, it just gives an example of tags that are to be preserved in one instance. Mathias' answer gives a solution through a hard-coded whitelist method. My answer provides a solution through a variable blacklist method for added flexibility. Neither are wrong or right, just alternative solutions to the original question.
    – theyetiman
    May 15, 2017 at 14:34
9

Try the following, you might find it a bit neater than the other proposed solutions:

public static int RemoveNodesButKeepChildren(this HtmlNode rootNode, string xPath)
{
    HtmlNodeCollection nodes = rootNode.SelectNodes(xPath);
    if (nodes == null)
        return 0;
    foreach (HtmlNode node in nodes)
        node.RemoveButKeepChildren();
    return nodes.Count;
}

public static void RemoveButKeepChildren(this HtmlNode node)
{
    foreach (HtmlNode child in node.ChildNodes)
        node.ParentNode.InsertBefore(child, node);
    node.Remove();
}

public static bool TestYourSpecificExample()
{
    string html = "<p>my paragraph <div>and my <b>div</b></div> are <i>italic</i> and <b>bold</b></p>";
    HtmlDocument document = new HtmlDocument();
    document.LoadHtml(html);
    document.DocumentNode.RemoveNodesButKeepChildren("//div");
    document.DocumentNode.RemoveNodesButKeepChildren("//p");
    return document.DocumentNode.InnerHtml == "my paragraph and my <b>div</b> are <i>italic</i> and <b>bold</b>";
}
5

Before removing a node, get its parent and its InnerText, then remove the node and re-assign the InnerText to the parent.

var parent = node.ParentNode;
var innerText = parent.InnerText;
node.Remove();
parent.AppendChild(doc.CreateTextNode(innerText));
5
  • InnerText ruins the hierachy. Imagine more depth, such as the following: <p>my <b>paragraph <div>and my <b><span><i>div</i></span></b></div> are <i>italic</i> and <b>bold</b></b></p>. InnerText screws up the HTML and converts it to text, but that's not what I want in all scenarios. I still want the HTML of the allowed tags. Oct 8, 2012 at 18:37
  • @MathiasLykkegaardLorenzen - My point is that you do this with the unwanted elements only.
    – Oded
    Oct 8, 2012 at 18:42
  • Yes. But what if you go through this data here. lalala <span>omg <b>this</b> is bold</span>. First, you discover the span element. It's not allowed, so you exchange it with its InnerText value. However, that ruins the inner b tags that I still need. I hope that explains it better. Oct 8, 2012 at 18:44
  • 1
    @MathiasLykkegaardLorenzen - Sure, you can simply do the same but with InnerHtml of the node instead of the parent (that is, take the InnerHtml of the node and replace the parent InnerHtml after removing the node). You can do this recursively with the node's InnerHtml too.
    – Oded
    Oct 8, 2012 at 18:46
  • Thanks - I'll try that and get back to you. Oct 8, 2012 at 18:48
3

If you do not want to use Html agility pack and still want to remove Unwanted Html Tag than you can do as given below.

public static string RemoveHtmlTags(string strHtml)
    {
        string strText = Regex.Replace(strHtml, "<(.|\n)*?>", String.Empty);
        strText = HttpUtility.HtmlDecode(strText);
        strText = Regex.Replace(strText, @"\s+", " ");
        return strText;
    }
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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