5

Here's 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 foreach loop li turns into a IDomObject variable and I can no longer drill down further into it.

Any suggestions? Here is the example HTML I'm 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 grab the text of each h2 element.

sergserg
  • 21,716
  • 41
  • 129
  • 182

1 Answers1

13

This is done in order to keep CsQuery consistent with jQuery which behaves the same way. You can convert it back to a CQ object by calling the .Cq() method as such

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

Or if you'd like 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 re-factored to the following if you'd like:

var texts = CQ.Create(htmlString)[".blog-accordion li header h2"]
              .Select(x=>x.Cq().Text());
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 1
    crikey i just edited your answer twice since I couldn't remember that Create() binds to a new dom. That's what a week off did to my old brain. `Cq()` creates a selection set from its argument, but still bound to the same DOM so you need to use `Find` to search within it, whereas `[..]` will select against the original DOM. `Create` always makes a new dom from its argument. – Jamie Treworgy Mar 31 '13 at 02:16
  • 1
    Thanks :) Glad to see you're back on you feet responding to pings. @Serg in case you don't know, Jamie is the guy who created and is developing CsQuery. – Benjamin Gruenbaum Mar 31 '13 at 02:20