Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was checking this question C# remove first wraping div my problem is similar, but I need to remove all the wraping divs, without removing those that might be in the middle of the string. For example, what I expect to do is:

Actual string:
<div><div><div><div><p>This is a test</p><ul><li>a</li><li><div>b</div></li><li>c</li></ul></div></div></div></div>
desired result after function
<p>This is a test</p><ul><li>a</li><li><div>b</div></li><li>c</li></ul>

I've been trying to make this function recursive, by stopping the call when its not getting any delelteable characters. However I get System.ArgumentOutOfRangeException: Index was out of range. exception when I pass a string without divs

 private string RemoveWrapingDiv(string html)
        {
            string result = string.Empty;

            if (!string.IsNullOrEmpty(html))
            {
                var start_idx = html.IndexOf(">", html.IndexOf("<div", StringComparison.InvariantCulture), StringComparison.InvariantCulture) + 1;
                var last_idx = html.LastIndexOf("</div>", StringComparison.InvariantCulture);
              
                result = html.Substring(start_idx, last_idx - start_idx);
            }

            return result;
        }

My question, how can I make this function recursive with a safe check to avoid exceptions? Do we need to make it recursive, or there's an easier way? Thanks!!

question from:https://stackoverflow.com/questions/65941606/c-sharp-remove-all-the-wraping-divs-for-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
154 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you only want to remove the div tags from the beginning and end of the string, keeping the ones in the middle, as well as any other HTML tag, then this should work:

    private static string RemoveWrapingDiv(string originalString)
    {
        var openingTag = "<div>";
        var closingTag = "</div>";
        var processedString = originalString;
        while (processedString.StartsWith(openingTag))
        {
            processedString = processedString.Substring(openingTag.Length, processedString.Length - openingTag.Length - closingTag.Length);
        }
        return processedString;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...