HTML agility pack - removing unwanted tags without removing content?

c# html-agility-pack

Question

There are a couple questions here that are similar to mine, but they don't precisely discuss the same issue.

To eliminate unnecessary tags from my HTML without losing the text they contain, I wish to utilize the Agility Pack for HTML.

In my situation, for example, I would want to keep the tags "b ", "i " and "u ".

And given an input such as:

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

The HTML that results should be:

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

I tried utilizingHtmlNode 's Remove nonetheless, it also deletes my material. Any recommendations?

1
44
11/23/2017 2:22:14 PM

Accepted Answer

I created an algorithm using Oded's recommendations. This is it. Works perfectly.

All tags are removed except one.strong , em , u and nodes for raw text.

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;
}
57
11/12/2016 12:37:12 AM

Popular Answer

How to recursively delete an unwelcome list of html tags from an html string

I updated @mathias' extension technique based on his response so that you may provide a list of tags to exclude as a filter.List<string> (e.g. {"a","p","hr"} ). In order for the logic to correctly recurse, I also made some corrections:

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;
    }


Related Questions





Related

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