我如何獲得所有兄弟ul標籤?

html-agility-pack

這是一個HTML片段:來自: http//www.sphere-light.com/compatibility/maker/id/4/

<h3 class="my-subject">a</h3>

<ul class='ex'>....</ul>
<ul class='ex'>....</ul>
<ul class='ex'>....</ul>
<ul class='ex'>....</ul>
<ul class='ex'>....</ul>
<ul class='ex'>....</ul>

<h3 class="my-subject">b</h3>

<ul class='ex'>....</ul>
<ul class='ex'>....</ul>
<ul class='ex'>....</ul>
<ul class='ex'>....</ul>
<ul class='ex'>....</ul>
<ul class='ex'>....</ul>

如何才能通過<h3 class="my-subject">a</h3>獲得6個兄弟姐妹ul.ex

並通過<h3 class="my-subject">b</h3>獲得下一個6 ul

一般承認的答案

由於<ul>標籤的數量可能會有所不同,因此您可以採取幾種方法。

使用XPath:

var h3Xpath = "//h3[@class='my-subject']";
var query = doc.DocumentNode.SelectNodes(h3Xpath);
foreach (var h3 in query)
{
    var value = h3.InnerText;
    var ulXpathFmt = "following-sibling::ul[@class='ex' and " +
        "preceding-sibling::h3[@class='my-subject'][1]='{0}']";
    var uls = h3.SelectNodes(String.Format(ulXpathFmt, value));
    // do something with the uls
}

我通常不會單獨使用XPath,而是混合使用一些LINQ。

var h3Xpath = "//h3[@class='my-subject']";
var query = doc.DocumentNode.SelectNodes(h3Xpath);
foreach (var h3 in query)
{
    var value = h3.InnerText;
    var ulXpathFmt = "following-sibling::ul[@class='ex' and " +
        "preceding-sibling::h3[@class='my-subject'][1]='{0}']";
    var uls = h3.SelectNodes(String.Format(ulXpathFmt, value));
    // do something with the uls
}



許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因