Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

.net - 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.

How can I procede? the HTML to be eliminated will always be that extra div

question from:https://stackoverflow.com/questions/65833226/c-sharp-remove-first-wraping-div

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...