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