C#删除第一个环绕div [英] C# remove first wraping div
问题描述
我正在尝试删除报告字符串中出现的第一个.
I'm trying to remove the first that appears in my reporting string.
Actual result:
<div><div><p>This is a test</p><ul><li>a</li><li>b</li><li>c</li></ul></div></div>
Expected result
<div><p>This is a test</p><ul><li>a</li><li>b</li><li>c</li></ul></div>
我一直在尝试将整个字符串转换为数组,这样我就可以删除它的第一个和最后一个元素,但是由于没有逗号或空格,我很难拆分它.
I've been trying to convert the whole string into an array so I can just remove the first and last element of it, but I'm having a hard time splitting it since there are no commas or spaces.
我如何进行?要删除的HTML将始终是多余的div
How can I procede? the HTML to be eliminated will always be that extra div
推荐答案
此方法将考虑您在第一个div中具有属性的情况(IE < div class ='bla'>< div>文本</div></div>
).为了完整起见并避免未处理的异常,您应该检查边缘情况(例如空字符串,格式错误的html ...)
This method will take into account the case scenario where you have an attribute in the first div (I.E. <div class='bla'> <div> text </div> </div>
).
For completeness and to avoid unhandled exception you should check for edge cases (such as empty strings, malformed html...)
public string InnerDiv(string html)
{
var start_idx = html.IndexOf(">", html.IndexOf("<div", StringComparison.InvariantCulture), StringComparison.InvariantCulture) + 1;
var last_idx = html.LastIndexOf("</div>", StringComparison.InvariantCulture);
return html.Substring(start_idx, last_idx - start_idx);
}
这篇关于C#删除第一个环绕div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!