htmllaglitypack从parentnode获取特定节点



考虑以下HTML

<li class="">
<a href="/package/tar/v/5.0.6" class="_132722c7 f5 black-60 lh-copy code link underline-hover" title="5.0.6">5.0.6</a>
<div class="c440844e mh2 h1"></div>
<code class="downloads">65</code>
<ul class="c495d29d list ml0 pl0 _8aa9368d">
<li>
<div class="c440844e mh2 h1"></div>
<code class="ccbecba3 f5 black-60 lh-copy">
<time datetime="2021-07-23T22:44:40.117Z" title="24-7-2021 00:44:40">3 months ago</time>
</code>
</li>
</ul>
</li>

我想获得时间元素的datetime属性的前4个字符。我通过下面的代码找到了这个特定的li元素。

htmlDoc2.DocumentNode.SelectSingleNode("//a[@title='"+ entry.Value + "']").ParentNode

我试着用下面的代码获取属性,但它不起作用。

var iets = htmlDoc2.DocumentNode.SelectSingleNode("//a[@title='"+ entry.Value + "']").ParentNode       
.SelectSingleNode("//time").Attributes["datetime"].Value.Substring(0,4);

但是当运行这个"将只返回ul列表中第一个时间元素的datetime属性。我怎样才能改变它,使它实际获得ParentNode的时间属性?

试试这个。我在内部选择中获取父元素的XPath,并将所需的元素添加到外部选择中。

请注意,这是在假设标题是唯一的情况下工作的,否则您将始终获得第一个匹配。

htmlDoc2.DocumentNode.SelectSingleNode(
$"{htmlDoc2.DocumentNode.
SelectSingleNode("//a[@title='"+ entry.Value +"']")
.ParentNode.XPath}//time")
.Attributes["datetime"].Value.Substring(0, 4)