HtmlAgility检查是否存在具有特定名称的子类

时间:2015-11-25 07:36:25

标签: c# html-agility-pack

<li class="sn-g">
     <span class="num">1</span>
     <span class="sym_first">
          <a class="icon>&nbsp;</a>
     </span>
     <span class="def">...text</span>
</li>

我的HTML页面包含此类子类。但是,sym_first类始终不存在。使用HTMLAgility我想查找网页中是否存在sym_first类。如果它存在,我想从def类获取InnerText。

foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//span[@class='" + sng + "']"))
{
   //How do I write this block?
   if(doc.DocumentNode.SelectNodes("//span[@class='" + symfirst + "']").Contains(xxx)
   {
      //get inner text
   }
} 

1 个答案:

答案 0 :(得分:1)

您可以尝试使用SelectSingleNode()并检查返回值是否不是null

if(doc.DocumentNode.SelectSingleNode("//span[@class='sym_first']") != null)
{
    //get inner text
}

或者,如果您要检查当前sym_first内的li课程(假设您在相关代码段中循环显示li):

if(node.SelectSingleNode("span[@class='sym_first']") != null)
{
    //get inner text
}

更新:

为了回应下面评论中报告的错误,请尝试检查def类是否也存在:

var sym_first = node.SelectSingleNode("span[@class='sym_first']");
var def = node.SelectSingleNode("span[@class='def']");
if(sym_first != null && def != null)
{
    //get inner text
}

根据要求,您可能只希望首先通过具有这些特定内容的li元素进行迭代:

var query = "//li[@class='sn-g'][span[@class='sym_first'] and span[@class='def']]";
foreach (HtmlNode node in doc.DocumentNode.SelectNodes(query))
{
   //get inner text
}