Wednesday, October 20, 2010

Using jquery selectors on server side(C#)

Something that i have been looking for a long time
is to use jquery selectors on the server side.
if found a great solution at fizzler project
fizzler is .NET CSS Selector Engine and you can download it from here.
from fizzler site:
A .NET library to select items from a node tree based on a CSS selector. The default implementation is based on HTMLAgilityPack and selects from HTML documents

all you have to is to download fizzler package
and add reference to this dll files:
- Fizzler.Systems.HtmlAgilityPack.dll
- Fizzler.Systems.XmlNodeQuery.dll
- HtmlAgilityPack.dll

here you can see a useful samples:

HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
html.LoadHtml(
@"<html>
<head></head>
<body>
<div id='content'>
<a target='_blank' href='http://yosi-havia.blogspot.com' class='FirstName'>Yosi</a>
<a href='http://yosi-havia.blogspot.com' class='LastName'>Havia</a>
</div>
</body>
</html>");
HtmlNode document = html.DocumentNode;

//@@@ get all elements with content id in html(result: 1 element)
IEnumerable<HtmlNode> list1 = document.QuerySelectorAll("#content");
List<HtmlNode> lst1 = list1.ToList<HtmlNode>();

//@@@ get all elements with FirstName class name in html(result: 1 element)
IEnumerable<HtmlNode> list2 = document.QuerySelectorAll(".FirstName");
List<HtmlNode> lst2 = list2.ToList<HtmlNode>();

//@@@ get all anchor tags in html(result: 2 elements)
IEnumerable<HtmlNode> list3 = document.QuerySelectorAll("a");
List<HtmlNode> lst3 = list3.ToList<HtmlNode>();

//@@@ get all elements in html(result: 6 elements)
IEnumerable<HtmlNode> list4 = document.QuerySelectorAll("*");
List<HtmlNode> lst4 = list4.ToList<HtmlNode>();

//@@@ get element with attribue name 'target' that starts with '_bl' in html(result: 1 element)
IEnumerable<HtmlNode> list5 = document.QuerySelectorAll("a[target^='_bl']");
List<HtmlNode> lst5 = list5.ToList<HtmlNode>();

No comments: