C# parse html with xpath

c# html-agility-pack xpath

Question

I'm trying to parse out stock exchange information whit a simple piece of C# from a HTML document. The problem is that I can not get my head around the syntax, the tr class="LomakeTaustaVari" gets parsed out but how do I get the second bit that has no tr-class?

Here's a piece of the HTML, it repeats it self whit different values.

<tr class="LomakeTaustaVari">
    <td><div class="Ensimmainen">12:09</div></td>
    <td><div>MSI</div></td>
    <td><div>POH</div></td>
    <td><div>42</div></td>
    <td><div>64,50</div></td>
</tr>
<tr>
    <td><div class="Ensimmainen">12:09</div></td>
    <td><div>SRE</div></td>
    <td><div>POH</div></td>
    <td><div>156</div></td>
    <td><div>64,50</div></td>
</tr>

My C# code:

{
    HtmlAgilityPack.HtmlWeb web = new HtmlWeb();
    HtmlAgilityPack.HtmlDocument doc = web.Load ("https://www.op.fi/op/henkiloasiakkaat/saastot-ja-sijoitukset/kurssit-ja-markkinat/markkinat?sivu=alltrades.html&sym=KNEBV.HSE&from=10:00&to=19:00&id=32453");

    foreach (HtmlNode row in doc.DocumentNode.SelectNodes("//tr[@class='LomakeTaustaVari']")) 
    {
        Console.WriteLine(row.InnerText);     
    }
    Console.ReadKey();
}

Popular Answer

Try to use the next xpath //tr[preceding-sibling::tr[@class='LomakeTaustaVari']]:

var nodes = doc.DocumentNode.SelectNodes("//tr[preceding-sibling::tr[@class='LomakeTaustaVari']]");

It should select nodes that have preceding node tr with class LomakeTaustaVari.

Just FYI: if no nodes found, SelectNodes method returns null.




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