【问题标题】:Extract content within a div tag ignoring other tags inside提取 div 标签中的内容,忽略其中的其他标签
【发布时间】:2016-07-27 05:25:11
【问题描述】:

以下是示例 html 源代码

<div id="page2" dir="ltr">

<p>This text I dont want to extract</p>
 This is the text which I want to extract
</div>

不管 div 标签的属性如何,我只想提取 div 标签文本,而忽略 div 标签内的其他标签文本。

在上面的示例中,我不想在&lt;p&gt;&lt;/p&gt; 标记中提取文本,但我想在&lt;div&gt;&lt;/div&gt; 标记中提取文本,即“这是我要提取的文本

XmlNodeList DivNodeList = xDoc.GetElementsByTagName("div");
string DivInnerText;
for (int i = 0; i < DivNodeList.Count; i++)
{
if (!DivNodeList[i].InnerXml.Contains("p"))
{
DivInnerText = DivNodeList[i].InnerText.Trim();
Div_List.Add(DivInnerText);
}
} 

但是上面的代码没有按预期工作,因为我正在检查 p 标签是否存在,然后只提取文本。显然,如果 p 标签存在,它就不会进入 div 标签的内部文本,并且包含所有组合的文本,无论其中的标签是什么。

非常感谢您对此的任何帮助。

【问题讨论】:

    标签: c#


    【解决方案1】:

    对于 HTML 处理,您应该尝试 HtmlAgilityPack 库。 您的要求应该很容易做到。 看看:http://www.c-sharpcorner.com/UploadFile/9b86d4/getting-started-with-html-agility-pack/

    【讨论】:

      【解决方案2】:

      使用 JQuery,您可以这样做:

      $("#page2").clone().children().remove().end().text();
      

      Example

      功劳应归于“DotNetWala”- check his answer here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-27
        • 1970-01-01
        • 2017-08-15
        • 2019-05-22
        • 1970-01-01
        • 1970-01-01
        • 2016-07-23
        相关资源
        最近更新 更多