HtmlAglitityPack 从父节点获取特定节点
HtmlAglityPack get specific node from 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>
我想获取时间元素的日期时间属性的前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);
但是当 运行 这个“iets”将只是 return ul 列表中第一个时间元素的 datetime 属性。我怎样才能改变它,让它真正获得 ParentNode 的时间属性?
试试这个。我在内部 select 中获取了 parent 的 XPath,并将所需的元素添加到外部 select.
请注意,这是基于标题唯一的假设,否则您将始终获得第一个匹配项。
htmlDoc2.DocumentNode.SelectSingleNode(
$"{htmlDoc2.DocumentNode.
SelectSingleNode("//a[@title='"+ entry.Value +"']")
.ParentNode.XPath}//time")
.Attributes["datetime"].Value.Substring(0, 4)
考虑以下 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>
我想获取时间元素的日期时间属性的前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);
但是当 运行 这个“iets”将只是 return ul 列表中第一个时间元素的 datetime 属性。我怎样才能改变它,让它真正获得 ParentNode 的时间属性?
试试这个。我在内部 select 中获取了 parent 的 XPath,并将所需的元素添加到外部 select.
请注意,这是基于标题唯一的假设,否则您将始终获得第一个匹配项。
htmlDoc2.DocumentNode.SelectSingleNode(
$"{htmlDoc2.DocumentNode.
SelectSingleNode("//a[@title='"+ entry.Value +"']")
.ParentNode.XPath}//time")
.Attributes["datetime"].Value.Substring(0, 4)