Do any jQuery-like html element selector libraries exist in the Dot Net world? I am building an application which involves huge amount of html parsing.
Say I want to enumerate all 'href's and 'src's inside only a selected 'div's having its id like "post_message_%". Or say want to select the name and value strings within a form with a specific id or input type(eg. hidden or radio)
I can write the code..but first looking for any existing solution, so that I can use it and save my time for something else.
A little late to the game, but here's another alternative. CsQuery is a complete port of jQuery in .NET4. It's on NuGet as CsQuery. It's stable and feature complete, including all CSS3 selectors and DOM manipulation methods. It's also fully indexed, making selectors orders of magnitude faster than HTML Agility Pack.
The syntax looks like this (copying example above)
CQ doc = CQ.CreateFromFile("file.htm");
foreach (IDomObject link in doc["a"]) {
var attr = link["href"];
link["href"] = FixLink(attr);
}
The property indexer syntax for a CQ object is the same as the default jQuery method to run a selector, e.g. $('a'). On a DomObject (an element) it returns the attribute value.
In addition to CSS selectors, CsQuery also implements all the jQuery methods, so you could do this as:
doc.Each((i,e)=> {
var el = CQ.Create(e); // or shorthand: var el = e.Cq()
el.Attr("href",FixLink(el.Attr("href"))
});
The syntax e.Cq() is the C# version of wrapping an element in a jQuery object, like var el = $(e). Since the value of the $ syntax is its brevity, and there's no way to create a default static method in C#, a method Cq() on elements is provided as shorthand to wrap an element in a CQ object.
You should check out the Html Agility pack, available here. Here's a use case from their website, that uses XPATH selectors:
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With