0

我有一个如下所示的 html 文件

  <div>

  <div style="margin-left:0.5em;">
  <div class="tiny" style="margin-bottom:0.5em;">
  <b><span class="h3color tiny">This review is from: </span>You Meet</b>
  </div>
  If you know Ron Kaufman as I do ...
  <br /><br />Whether you're the CEO....
  <br /><br />Written in a distinctive, ...
  <br /><br />My advice? Don't just get one copy
  <div style="padding-top: 10px; clear: both; width: 100%;"></div>
  </div>

  <div style="margin-left:0.5em;">
  <div class="tiny" style="margin-bottom:0.5em;">
  <b><span class="h3color tiny">This review is from: </span>My Review</b>
  </div>
  I became a fan of Ron Kaufman after reading an earlier book of his years ago...
  <div style="padding-top: 10px; clear: both; width: 100%;"></div>
  </div>

  </div>

我想获得没有任何 html 标签的评论文本。我现在使用下面的代码

  foreach (HtmlNode divReview in doc.DocumentNode.SelectNodes(@"//div[@style='margin-left:0.5em;']"))   
   {
      if (divReview != null)
          {

 review.Add(divReview.Descendants("div").Where(d => d.Attributes.Contains("style") && 
 d.Attributes["style"].Value.Contains("padding-top: 10px; clear: both; width: 100%;")).
                                          Select(d =>
 d.PreviousSibling.InnerText.Trim()).SingleOrDefault());  
          }
       }

只返回“我的建议?不要只得到一份”,我怎样才能得到整个文本?

更新:即使我删除所有

“兄弟”

来自 htmlnode 的标签,仍然在使用上面的代码时,我只得到“我的建议?不要只得到一份”部分!任何意见?

4

1 回答 1

0

我已将代码更新为:

var allText = (reviewDiv.Descendants("div")
  .First(div => div.Attributes["style"].Value == "padding-top: 10px; clear: both; width: 100%;")
  .SelectNodes("./preceding-sibling::text()") ?? new HtmlNodeCollection(null)) 
  .Select(text => text.InnerText);

这应该返回一个 IEnumerable 字符串,其中包含具有复杂样式的 div 前面的文本。

如果没有更多周围的 HTML,很难判断这是否正是您所追求的。我目前猜测您选择了一个 div,并且该 div 是整个文本块的直接父级(鉴于您对 reviewDiv 的引用)。您的 HTML 示例似乎不包含这段 HTML,所以我在这里做一些假设。

使用以下输入:

<div><div class="tiny" style="margin-bottom:0.5em;">
<b><span class="h3color tiny">This review is from: </span>You Meet</b>
</div>
If you know Ron Kaufman as I do ...
<br /><br />Whether you're the CEO....
<br /><br />Written in a distinctive, ...
<br /><br />My advice? Don't just get one copy
<div style="padding-top: 10px; clear: both; width: 100%;"></div></div>

它提取了这个:

如果你和我一样认识罗恩考夫曼……
无论你是首席执行官……都
写得与众不同,……
我的建议?不要只得到一份

要构建我使用的单个字符串:string extractedText = string.Join("", allText);

于 2013-05-08T20:18:16.500 回答