heyaa heyaa - 3 years ago 202
HTML Question

get all td in XPath c#

I am trying to parse HTML using HtmlAgilityPack in C#. I have

21 tr items
and each tr items have
7 td items
. How can I get all tr and td items in order? Now I can get only one tr item and its 7 td items.

Here is my C# Code:

var url = "url";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string sourceCode = sr.ReadToEnd();

HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(sourceCode);


var name = document.DocumentNode.SelectNodes("//*[@id=\"searchResultsTable\"]/tbody/tr[1]/td[2]/a[1]")[0].InnerText;
var year = document.DocumentNode.SelectNodes("//*[@id=\"searchResultsTable\"]/tbody/tr[1]/td[3]")[0].InnerText;
var km = document.DocumentNode.SelectNodes("//*[@id=\"searchResultsTable\"]/tbody/tr[1]/td[4]")[0].InnerText;
var color = document.DocumentNode.SelectNodes("//*[@id=\"searchResultsTable\"]/tbody/tr[1]/td[5]")[0].InnerText;
var price = document.DocumentNode.SelectNodes("//*[@id=\"searchResultsTable\"]/tbody/tr[1]/td[6]")[0].InnerText;
var date = document.DocumentNode.SelectNodes("//*[@id=\"searchResultsTable\"]/tbody/tr[1]/td[7]")[0].InnerText;
var location = document.DocumentNode.SelectNodes("//*[@id=\"searchResultsTable\"]/tbody/tr[1]/td[8]")[0].InnerText;


I tried to use
[@id=\"searchResultsTable\"]/tbody/tr[1]/td[position()<8]
but is returns only /n

Answer Source

Try below code (not tested. Chances of compile errors. But gives you an Idea.)

Comments in the code gives you more details.

//GET THE TABLE NODE
HtmlNode table = document.DocumentNode.SelectSingleNode("//*[@id='searchResultsTable']");

//LOOP THROUGH THE TABLE NODE AND FIND EACH TR 
foreach (HtmlNode row in table.SelectNodes("//tr")) {

      //PRINT HERE WHATEVER YOU WANT FOR EACH ROW.
      Console.WriteLine("New Row");

      //LOOP THROUGH THE ALL TD OF EACH TR
      foreach (HtmlNode cell in row.SelectNodes("//td")) {
          //PRINT HERE EACH TD
          Console.WriteLine("cell: " + cell.InnerText);
      } //END TD

}//END TR
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download