CsQuery for parsing a collection of li elements

Here is my code:

CQ dom = CQ.Create(htmlString);
var items = dom[".blog-accordion li"];

foreach (var li in items)
{
    var newTournament = false;
    var test = li["header h2"];
}

Inside the loop, foreach ligoes into a variable IDomObject, and I can no longer go into it.

Any suggestions? Here is an example of HTML that I am trying to parse:

<ul>
  <li>
    <header>
      <h2>Test</h2>
    </header>
  </li>
  <li>
    <header>
      <h2>Test 2</h2>
    </header>
  </li>
  <li>
    <header>
      <h2>Test 3</h2>
    </header>
  </li>
</ul>

I need to capture the text of each h2 element.

+5
source share
1 answer

This is done in order to keep CsQueryin line with jQuerythat which behaves the same. You can convert it back to an object CQby calling the method .Cq()as such

foreach (var li in items)
{
    var newTournament = false;
    var test = li.Cq().Find("header h2");
}

Or, if you want more jQueryish syntax , the following also works:

foreach (var li in items)
{
    var newTournament = false;
    var test = CQ.Create(li)["header h2"];
}

Your code could be reinstalled if you wanted:

var texts = CQ.Create(htmlString)[".blog-accordion li header h2"]
              .Select(x=>x.Cq().Text());
+12
source

All Articles