by
0
8
5,457
14
Top 1% !
Famous
Pearl of Wisdom
Tagged
Specified
Refined
Debate
OpenSource
Popularity: 1432nd place

Published on:

.NETFramework4.0
Architecturex86_64
Extension.cs
InputName0pageString
InputName1tagName
InputType0string
InputType1string
LanguageCSharp
LicenseMIT_X11
MethodNameRemoveHtmlTag
OSWindows
OutputTypestring

C#: How to remove a given tag (and all its content) from an HTML page

This method removes the content of all the occurrences of the given tag in the given page
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/25652/C---How-to-remove-a-given-tag-(and-all-i?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
static public string RemoveHtmlTag(string pageString, string tagName) { string output = pageString; int exprIni = 0; int firstChar = 0; int lastChar = 0; // find html element exprIni = output.IndexOf("<" + tagName, 0, output.Length, StringComparison.InvariantCultureIgnoreCase); while (exprIni > 0) { // extract the html firstChar = exprIni; // find <tag ... /> lastChar = output.IndexOf("/>", (firstChar + 1)) + 1; int nextCloseTag = output.IndexOf('>', (firstChar + 1)); // closed with </tag> marker.. if ((lastChar <= 0) || (nextCloseTag < lastChar)) { // find </tag> lastChar = output.IndexOf("</" + tagName, (firstChar + 1), (output.Length - firstChar - 1), StringComparison.InvariantCultureIgnoreCase); lastChar = output.IndexOf('>', (lastChar + 1)); } if ((firstChar < 0) || (lastChar <= 0) || (firstChar == lastChar)) return output.Substring(0, firstChar); else { output = String.Format("{0} {1}", output.Substring(0, firstChar).Trim(), output.Substring((lastChar + 1), (output.Length - lastChar - 1)).Trim()); } exprIni = output.IndexOf("<" + tagName, 0, output.Length, StringComparison.InvariantCultureIgnoreCase); } return output; }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus