C# HtmlAgilityPack解析<ul>

3
我希望能解析以下HTML。
我目前拥有的是:
var node = document.DocumentNode.SelectSingleNode("//div[@class='wrapper']");

这个HTML是

<div class="wrapper">
    <ul>
                <li data="334040566050326217">
                    <span>test1</span>
                </li>
                <li data="334040566050326447">
                    <span>test2</span>
                </li>
    </ul>

我需要从 li data 中获取数字,以及在 span 标签之间的值。感谢您的帮助。
1个回答

6

这样的东西可能适合您的需求。

//Assumes your document is loaded into a variable named 'document'

List<string> dataAttribute = new List<string>(); //This will contain the long # in the data attribute
List<string> spanText = new List<string>();      //This will contain the text between the <span> tags
HtmlNodeCollection nodeCollection = document.DocumentNode.SelectNodes("//div[@class='wrapper']//li");

foreach (HtmlNode node in nodeCollection)
{
    dataAttribute.Add(node.GetAttributeValue("data", "null"));
    spanText.Add(node.SelectSingleNode("span").InnerText);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接