In the last in the series of posts on writing a .NET application to communicate over HTTP, I thought I'd talk about
HtmlAgilityPack (download available
here). This tool allows you to write XPATH-like expressions to parse HTML files easily.
In my application, I upload a file and some form variables to a web server, which then responds with an HTML page. On that HTML page, buried in the middle, is a confirmation ID. In order to easily grab that ID and store it for later use, I use code like the following:
private string CheckResponse(string response)
{
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(response);
HtmlNodeCollection coll = doc.DocumentNode.SelectNodes("//td[@id]");
if (coll == null)
return null;
foreach (HtmlNode node in coll)
{
if (node.Attributes["id"].Value.Equals("confirmation"))
{
return node.InnerText;
}
}
return null;
}