Thursday, May 26, 2005

HtmlListToArrayList (C#)

This function returns an ArrayList when you supply a string containing a list as the parameter.

string text = "<ul><li class='foo' id='bar'>Item 1</li><li></li><li>Item 2</li><li>Item 3</li></ul>";
ArrayList ar;
ar = HtmlListToArrayList(text);
Response.Write(ar[1]); // returns 'Item 2'
public System.Collections.ArrayList HtmlListToArrayList(string input)
{
 string tag = @"</?(li)(\s+\w+=(\w+|""[^""]*""|'[^']*'))*\s*?/?>";
 string pat = tag + "([^<]+)";
 System.Collections.ArrayList ar = new System.Collections.ArrayList();
 // Compile the regular expression.
 System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(pat, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
 foreach(System.Text.RegularExpressions.Match m in r.Matches(input))
 {
  ar.Add(m.Groups[4].Value);
 }
 return ar;
}

Tags: ,

No comments: