Html Agility Pack – Rule the DOM
18/02/2010 Leave a comment
Html Agility Pack is one of best tool forcing DOM in .net by Codeplex.
What is exactly the Html Agility Pack (HAP)?
This is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT (you actually don’t HAVE to understand XPATH nor XSLT to use it, don’t worry…). It is a .NET code library that allows you to parse “out of the web” HTML files. The parser is very tolerant with “real world” malformed HTML. The object model is very similar to what proposes System.Xml, but for HTML documents (or streams).
Html Agility Pack now supports Linq to Objects (via a LINQ to Xml Like interface). Check out the new beta to play with this feature
Sample applications:
- Page fixing or generation. You can fix a page the way you want, modify the DOM, add nodes, copy nodes, well… you name it.
- Web scanners. You can easily get to img/src or a/hrefs with a bunch XPATH queries.
- Web scrapers. You can easily scrap any existing web page into an RSS feed for example, with just an XSLT file serving as the binding. An example of this is provided.
Example Code:
HtmlDocument doc = new HtmlDocument(); doc.Load("file.htm"); foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"]) { HtmlAttribute att = link["href"]; att.Value = FixLink(att); } doc.Save("file.htm");
Codeplex project home:
http://htmlagilitypack.codeplex.com/
Download: 1.4.0 Beta 2 Version:
http://htmlagilitypack.codeplex.com/releases/view/33903
Good coding ….
.