<li class="sn-g">
<span class="num">1</span>
<span class="sym_first">
<a class="icon> </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
}