How to terminate a while loop when an Xpath query returns a null reference html agility pack -


i'm trying loop through every row of variable length table on webpage (http://www.oddschecker.com/golf/the-masters/winner) , extract data

the problem can't seem catch null reference , terminate loop without throwing exception!

int = 1; bool test = string.isnullorempty(doc.documentnode.selectnodes(string.format("//*[@id='t1']/tr[{0}]/td[3]/a[2]", i))[0].innertext);  while (test != true) {     string name = doc.documentnode.selectnodes(string.format("//*[@id='t1']/tr[{0}]/td[3]/a[2]", i))[0].innertext;     //extract data     i++; } 

try-catch statements don't catch either:

bool test = false; try {      string golfersname = doc.documentnode.selectnodes(string.format("//*[@id='t1']/tr[{0}]/td[3]/a[2]", i))[0].innertext;  }  catch  {       test = true;  }   while (test != true)  { ... 

the code logic bit off. original code, if test evaluated true loop never terminates. seems want checking in every loop iteration instead of once @ beginning.

anyway, there better way around. can select relevant nodes without specifying each <tr> indices, , use foreach loop through node set :

var nodes = doc.documentnode.selectnodes("//*[@id='t1']/tr/td[3]/a[2]"); foreach(htmlnode node in nodes) {     string name = node.innertext;     //extract data } 

or using for loop instead of foreach, if index of each node necessary "extract data" process :

for(i=1; i<=nodes.count; i++) {     //array index starts 0, unlike xpath element index     string name = nodes[i-1].innertext;     //extract data } 

side note : query single element can use selectsinglenode("...") instead of selectnodes("...")[0]. both methods return null if no nodes match xpath criteria, can checking against original value returned instead of against innertext property avoid exception :

var node = doc.documentnode.selectsinglenode("..."); if(node != null) {     //do } 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -