0

我有以下代码:

HtmlAgilityPack.HtmlNodeCollection nodeCollection = bodyNode.SelectNodes("//ul[@class='myClass']//li");

它抓住了大约 250LI

UL格式有点奇怪,它是这样的:

<ul>
    <li>
        <h5>Parent</h5>
        Some more tags here...
    </li>
    <li>
        <h4>Child of the prev li</h4>
    </li>
    <li>
        <h4>Child of the prev li</h4>
    </li>
    <!-- and so on -->
    <!-- Then again -->
    <li>
        <h5>Parent</h5>
        Some more tags here...
    </li>
    <li>
        <h4>Child of the prev li</h4>
    </li>
    <li>
        <h4>Child of the prev li</h4>
    </li>
    <!-- child li's are not constant, this is only for demo -->
</ul>

我需要将' sLI分成组,其中每个组包含父级LI和所有子级LI

有人可以帮忙吗?

4

2 回答 2

0

如果我理解正确,这就是你想要的

HtmlNodeCollection liList = doc.DocumentNode.SelectNodes("//ul//li");
List<List<HtmlNode>> liGroups = new List<List<HtmlNode>>();
List<HtmlNode> liGroup = null;
foreach (HtmlNode li in liList)
{
    if (li.InnerText.Contains("Parent"))
    {
        if (liGroup != null)
            liGroups.Add(liGroup);
        liGroup = new List<HtmlNode>();
        liGroup.Add(li);
    }
    else
    {
        liGroup.Add(li);
    }
}
liGroups.Add(liGroup);

最后您将拥有一个列表,该列表liGroups将包含其他列表liGroup。对于您上面的 html,它将显示liGroups有 2 liGroup,因为在您上面的 html 中,您有 2 个父母,并且两个父母liGroup都有 3 li(1 个父母 + 2 个孩子),因为父母双方都有相同数量的孩子。

之后,您可以随心所欲地使用它们,例如:

MessageBox.Show(liGroups[0][2].InnerText); //Show from the first group the 3rd's li InnerText
于 2013-06-14T16:37:19.797 回答
0
var tree = new Dictionary<HtmlNode, List<HtmlNode>>();
foreach (var node in nodeCollection)
    if (node.SelectSingleNode("h5[text()='Parent']") != null)
        tree.Add(node, new List<HtmlNode>());
    else
        tree.Last().Value.Add(node);

或者

var groups = nodeCollection.Group();

static class Extensions
{
    public static ILookup<HtmlNode, HtmlNode> Group(this HtmlNodeCollection collection)
    {
        return collection.Where(n => !n.IsParent()).ToLookup(n => n.GetParent());
    }

    public static bool IsParent(this HtmlNode node, string header = "Parent")
    {
        var h = node.Element("h5");
        return h != null && h.InnerText == header;
    }

    public static HtmlNode GetParent(this HtmlNode node)
    {
        while (!node.IsParent())
            node = node.PreviousSibling;
        return node;
    }
}
于 2013-06-12T17:52:58.543 回答