Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当Xpath查询返回空引用html敏捷包时,如何终止while循环_Xpath_Html Agility Pack_Nullreferenceexception - Fatal编程技术网

当Xpath查询返回空引用html敏捷包时,如何终止while循环

当Xpath查询返回空引用html敏捷包时,如何终止while循环,xpath,html-agility-pack,nullreferenceexception,Xpath,Html Agility Pack,Nullreferenceexception,我试图循环浏览网页()上可变长度表的每一行,并提取一些数据 问题是我似乎无法捕获空引用并终止循环,而不引发异常 int i = 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.Docume

我试图循环浏览网页()上可变长度表的每一行,并提取一些数据

问题是我似乎无法捕获空引用并终止循环,而不引发异常

int i = 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语句也无法捕获它:

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)
 {
...

代码逻辑有点错误。对于原始代码,如果
test
evaluated
true
循环将永远不会终止。似乎您希望在每个循环迭代中检查,而不是在开始时只检查一次

无论如何,有更好的办法。您可以选择所有相关节点,而无需指定每个
索引,并使用
foreach
循环遍历节点集:

var nodes = doc.DocumentNode.SelectNodes("//*[@id='t1']/tr/td[3]/a[2]");
foreach(HtmlNode node in nodes)
{
    string name = node.InnerText;
    //extract data
}
如果“提取数据”过程需要每个节点的索引,则使用
for
循环而不是
foreach

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

啊,太棒了,谢谢你!雅加达的天气怎么样?:)
var node = doc.DocumentNode.SelectSingleNode("...");
if(node != null)
{
    //do something
}