如何使用htmlAgilityPack获取没有标记的文本

时间:2013-05-08 16:13:32

标签: c# html xpath html-agility-pack

我有一个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());  
          }
       }

只返回“我的建议?不要只获得一份”,我怎样才能获得全文?

更新:即使我删除所有

“BR”

来自htmlnode的

标签,仍然在使用上面的代码时我只得到“我的建议?不要只获得一份”部分!有什么意见吗?

1 个答案:

答案 0 :(得分: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>

它提取了这个:

  

如果你像我一样了解Ron Kaufman ......     无论你是CEO ......     写在一个独特的,...
    我的建议?不要只获得一份副本

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