当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
evaluatedtrue
循环将永远不会终止。似乎您希望在每个循环迭代中检查,而不是在开始时只检查一次
无论如何,有更好的办法。您可以选择所有相关节点,而无需指定每个
索引,并使用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
}