gpt4 book ai didi

c# - 从具有特定类名的元素中选择值

转载 作者:行者123 更新时间:2023-11-30 22:08:38 25 4
gpt4 key购买 nike

我在解析外部 html 文件时遇到对象引用错误,我认为这是因为并非所有选定的元素都具有类名。这是我的代码:

foreach (HtmlNode link in doc.DocumentNode.Descendants("li").Where(i => i.Attributes["class"].Value == "name"))
{
string result = link.InnerText.Trim().Replace(" ", "");
Console.WriteLine(result);
}

如何只选择类名为“name”的值?

这是我要解析的 html 代码:

<li>
<span class="name">
<a href="/players/joe-bloggs.html">Joe,&nbsp;Bloggs</a>
</span>

<span class="country">
<img src="/img/flags/15x15/USA.gif" alt="USA"/>
United States
</span>
</li>
<li>
<span class="name">
<a href="/players/joe-bloggs.html">Joe,&nbsp;Bloggs</a>
</span>

<span class="country">
<img src="/img/flags/15x15/USA.gif" alt="USA"/>
United States
</span>
</li>
<li>
<span class="name">
<a href="/players/joe-bloggs.html">Joe,&nbsp;Bloggs</a>
</span>

<span class="country">
<img src="/img/flags/15x15/RSA.gif" alt="RSA"/>
South Africa
</span>
</li>

最佳答案

您应该选择 a 元素而不是 li 元素。及其具有 class 属性的 span 元素。我建议你使用谓词:

var links = doc.DocumentNode.SelectNodes("//li/span[@class='name']/a");

此 xpath 选择所有 span 元素,其 class 属性等于 name,然后选择 a 元素.

foreach (var a in links)
Console.WriteLine(a.InnerText);

对于您的示例 HTML 输出是:

Joe,&nbsp;Bloggs
Joe,&nbsp;Bloggs
Joe,&nbsp;Bloggs

旁注 - 您可以使用 HttpUtility.HtmlDecode(a.InnerText) 获取解码文本(不仅   将被替换)。


更新:解析播放器

var players = from p in doc.DocumentNode.SelectNodes("//li")
let name = p.SelectSingleNode("span[@class='name']/a")
let country = p.SelectSingleNode("span[@class='country']")
select new
{
Name = (name == null) ? null :
HttpUtility.HtmlDecode(name.InnerText.Trim()),
Country = (country == null) ? null :
HttpUtility.HtmlDecode(country.InnerText.Trim())
};

结果:

[
{
Name: "Joe, Bloggs",
Country: "United States"
},
{
Name: "Joe, Bloggs",
Country: "United States"
},
{
Name: "Joe, Bloggs",
Country: "South Africa"
}
]

关于c# - 从具有特定类名的元素中选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22143514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com