Friday, September 03, 2010

How to find html tags inside rendered html in code behind - Asp.net

This script grabs all the tags specified by a tag name. Like if you need to find all the image tags inside rendered html in code behind, you may achive your goal using following script. If you are looking to find the content of a given html element please refer this article.
protected override void Render(HtmlTextWriter writer)
{
    StringBuilder sb = new StringBuilder();
    HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb));
    base.Render(htw);
    string html = sb.ToString();
 
    string tag = "img";
 
    List<string> tags = new List<string>();
    int limit = 0, lb = 0, ub = 0;
    string startTag = string.Format("<{0}", tag);
    string endTag = string.Format(">", tag);
    string lHtml = html.ToLower();
    do
    {
        lb = lHtml.IndexOf(startTag, limit);
        if (lb > 0)
        {
            limit = ub = lHtml.IndexOf(endTag, lb) + endTag.Length;
            tags.Add(html.Substring(lb, ub - lb));
        }
        else limit = lb;
    }
    while (limit > 0);
    ///
    /// all the image tags are in tags list.
    ///
    writer.Write(html);
}

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...