将 div 内多个 <p> 标签的所有内容组合成一个字符串

Combine all the content from the multiple <p> tag inside a div, into a single string

我的 html 内容为:

<div class="editor-box">
   <div class="insert-ad">
     Some ad content
   </div>
   <p>paragraph 1</p>
   <p>paragraph2</p>
   <p>paragraph3</p>
   <div class="media ad-item">
        Another Ad Content
    </div>
   <p>Paragraph4</p>
   <p>Paragraph5/p>
   <p></p>
</div>

我想 merge <p> 元素中的所有文本一次变成一个字符串。

我的最终 OutputString 为:

string Output = "paragraph 1 paragraph2 paragraph3 Paragraph4 Paragraph5"

我试过:

var doc = await GetAsync(href);
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//div[@class='editor-box']/p"))
{
    string text = node.InnerText;
}

我已经从单个 <p> 元素中获取了文本,但是有什么方法可以通过单个查询 select 来自 <p> 的所有内容,这样我就不会需要循环所有节点并合并到另一个字符串对象中。

你可以试试这个... 如果您为 div 元素分配一些 id 并添加 runat=server.

System.IO.StringWriter sw = new System.IO.StringWriter();
       System.Web.UI.HtmlTextWriter htmltext = new System.Web.UI.HtmlTextWriter(sw);
                DivId.RenderControl(htmltext);
                string str = sw.GetStringBuilder().ToString();

这里DivIdid分配给div

出于任何原因,如果您不想手动遍历所有段落内容,您始终可以使用 LINQ 和 string.Join 来获得相同的结果。:

//1. Get the document
var doc = await GetAsync(href);

//2. Select all the paragraphs:
var paragraphNodes = doc.DocumentNode.SelectNodes("//div[@class='editor-box']/p");

//3. Select the content inside them:
var paragraphContentList = paragraphNodes.Select(node => node.InnerText);

//4. Join all the contents in a single string
var finalString = string.Join(" ", paragraphContentList);

//5. Done!
Console.WriteLine(finalString);

记得使用 LINQ 命名空间using System.Linq;