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:

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...