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

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
   }
} 

热门答案

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

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

或者如果你的意思是检查当前li sym_first类(假设你在相关的代码片段中循环遍历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
} 


Related

许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow