我如何获得所有兄弟ul标签?

时间:2012-02-15 06:19:15

标签: 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>

如何通过ul.ex

获得6个兄弟姐妹<h3 class="my-subject">a</h3>

并通过ul获取下一个<h3 class="my-subject">b</h3>

1 个答案:

答案 0 :(得分:1)

由于<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
}