Get text inside of a span

c# html-agility-pack

Question

I have an HTML page with this code

<span class="titoloSerie" style="font-size: 40px; color: #000000;">SHOW NAME</span>

I want to get "SHOW NAME". I tried the following code, but it didn't work:

var div = doc.DocumentNode.SelectNodes("//span[@class='titoloSerie']");

The compiler interrupts saying "div is null" (ok, I didn't handle the exception but I know it).

The following code is:

List<string> pageTitles = new List<string>();
foreach (var title in div)
{
    pageTitles.Add(title.InnerText);
}

The compiler quits in the foreach loop at "div" saying it's null.

Accepted Answer

Try this:

var rigaStagioneSerie = document.DocumentNode.SelectNodes("//td[@class='rigaStagioneSerie']");
List<string> pageTitles = new List<string>();

foreach (var title in rigaStagioneSerie)
{
    if (title.ChildNodes.Count == 1)
    {
        pageTitles.Add(title.InnerText.Replace("\n", string.Empty).Replace("\t", string.Empty));
    }

}

var titoloSerie = document.DocumentNode.SelectNodes("//span[@class='titoloSerie']");

foreach (var title in titoloSerie)
{
    pageTitles.Add(title.InnerText);
}

Try it here: .NET Fiddle




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why