CsQuery解析li项目的集合 [英] CsQuery to parse a collection of li items

查看:103
本文介绍了CsQuery解析li项目的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

foreach(项目中的变量)
{
var newTournament = false;
var test = li [header h2];
}

在foreach循环中 li 会变成一个 IDomObject 变量,我再也无法深入了解它。



有什么建议吗?这里是我试图解析的HTML示例:

 < ul> 
< li>
< header>
< h2>测试< / h2>
< / header>
< / li>
< li>
< header>
< h2>测试2< / h2>
< / header>
< / li>
< li>
< header>
< h2>测试3< / h2>
< / header>
< / li>
< / ul>

我需要获取每个h2元素的文本。

解决方案

这样做是为了保持 CsQuery 与<$一致c $ c> jQuery ,其行为方式相同。您可以通过调用 .Cq()方法将它转换回< CQ 对象。

  foreach(项目中的变量)
{
var newTournament = false;
var test = li.Cq()。Find(header h2);
}

或者如果您想要更多 jQuery ish语法,以下内容也适用:

  foreach(项目中的变量)
{
var newTournament = false;
var test = CQ.Create(li)[header h2];

如果您想要,您的代码可以重新分解为以下内容:

  var texts = CQ.Create(htmlString)[。blog-accordion li header header 2] 
。选择(X => x.Cq()文本());


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.

解决方案

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());

这篇关于CsQuery解析li项目的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆