我如何获得所有兄弟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 ulXpath = "following-sibling::*";
    var uls = h3.SelectNodes(ulXpath)
        .TakeWhile(tag => tag.Name == "ul" &&
                          tag.Attributes["class"].Value == "ex");
    // do something with the uls
}



许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因