Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# HtmlAgilityPack Select table from specific h2

I have some html:

<h2>Results</h2>
 <div class="box">
 <table class="tFormat">
      <th>Head</th>
      <tr>1</tr>
 </table>
</div>

<h2>Grades</h2>
 <div class="box">
 <table class="tFormat">
      <th>Head</th>
      <tr>1</tr>
 </table>
</div>

I was wondering how would I get the table under "Results"

I've tried:

        var nodes = doc.DocumentNode.SelectNodes("//h2");

        foreach (var o in nodes)
        {
            if (o.InnerText.Equals("Results"))
            {
                foreach (var c in o.SelectNodes("//table"))
                {
                    Console.WriteLine(c.InnerText);             
                }
            }
        }

It works but it also gets the table under Grades h2

like image 547
LuxC Avatar asked Dec 26 '12 12:12

LuxC


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

Is C programming hard?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


1 Answers

Note that the div is not hierarchically inside the header, so it doesn't make sense to look for it there.

This can work for you - it finds the next element after the title:

if (o.InnerText.Equals("Results"))
{
    var nextDiv = o.NextSibling;
    while (nextDiv != null && nextDiv.NodeType != HtmlNodeType.Element)
        nextDiv = nextDiv.NextSibling;
    // nextDiv should be correct here.
}

You can also write a more specific xpath to find just that div:

doc.DocumentNode.SelectNodes("//h2[text()='Results']/following-sibling::div[1]");
like image 54
Kobi Avatar answered Sep 29 '22 00:09

Kobi