Introduction
In one of the topics, HAP: What is HTML Agility Pack we have learned what is HAP and its uses. Here, we are going to explore yet another magnificent feature that the HAP technology facilitates us with, i.e. HTML Selectors using Html Agility Pack. A developer can select nodes using Html Agility Pack and use the selected nodes for various purposes. These are easy to learn and very useful as you would be realising it when you start to implement it.Nodes and selecting them
HTML is basically a Document Object Model (DOM) and primarily consists of a tree composed of nodes. Hierarchically, depending on our requirements, we develop the HTML code and thus pave way for the formation of nodes. Sometimes, it is necessary to be able to select the nodes for the given XPath or other times it might be the need of just one node. Thus, we should have HTML selectors using Html Agility Pack. Accordingly, we have two functions in HAP which are discussed below.Free Video Library: Learn HTML Agility Pack Step by Step
1. SelectNodes()
To select all the nodes that match with the expressions of the type HtmlAgilityPack.HtmlNode.XPath.It accepts parameters that are of XPath type.
When you use this function, it will return all the list of nodes that match the given parameters. If there is none that meet the criteria, then you could expect null as a result.
You could see how this function can be used through the following example.
var html = @" var html = @"<TD> </TD> <TD> <INPUT value=Technology> <INPUT value=Crowds> </TD> var htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(html); var node = htmlDoc.DocumentNode.SelectNodes("//td/input"); foreach (var node in nodes) { Console.WriteLine(node.Attributes["value"].Value); }
Output
Technology
Crowds
2. SelectSingleNode(String)
This function also serves for the same requirement but rather returns only one node. To be specific, its result contains the first node that matches the given XPath expression.SelectSingleNode is a type of function that takes in an XPath expression and produces a result that contains the first HtmlAgilityPack.HtmlNode. The return value could also be null if there are no matching nodes.
The example given below is a clear representation of this explanation.
var html = @" var html = @"<TD> </TD> <TD> <INPUT value=Technology> <INPUT value=Crowds> </TD> var htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(html); var node = htmlDoc.DocumentNode.SelectNodes("//td/input").First() .Attributes["value"].Value; Console.WriteLine(node);
Output
Technology
Post A Comment:
0 comments: