敏捷包 选择内部文本,但跳过特定标记

本文关键字:选择 内部 文本 | 更新日期: 2023-09-27 18:34:24

关于这样的示例:

<p>there is something here <span>we can't have this</span> again here <em>but we keep this one</em> we are good to go now </p>

有办法删除 span 节点,这样我只能获取所有其他标签的内部文本。但是我需要保留 span 标签,但在收到它时跳过他的内部文本。现在我有这个:

var paragraphe = html.DocumentNode.SelectNodes("p");
for (int i = 0; i < paragraphe.Count; i++)
{
    string innerTextOfP = paragraphe[i].InnerText;
    if (string.IsNullOrEmpty(innerTextOfP))
    {
        //Do something later.
    }
    else
    {
        //something is done here with the text I get.
    }
}

我能想到的最好的方法是有另一件事,例如:

var nodeSpan = html.DocumentNode.SelectNodes("span");

并在我使用字符串缓冲区迭代 P 部分的子级以获取文本并跳过内容时进行比较paragraphe.childNode = nodeSpan 但我认为敏捷包有另一种方法来做这种事情,但我不知道是什么。

就我而言,如果类是其他的,我还需要跳过 DIV(和他的孩子)的内容

,然后"contenu"

所以我打算为跨度做这件事的方式对 DIV 部分不利。

我应该如何使用敏捷包来做到这一点?

编辑:这种情况的预期结果将是:

string innerTextOfP = "there is something here again here but we keep this one we are good to go now"

敏捷包 选择内部文本,但跳过特定标记

您可以从段落中删除span子项:

var paragraphes = html.DocumentNode.SelectNodes("//p");
foreach (var p in paragraphes)
{
    var clone = p.Clone(); // to avoid modification of original html
    foreach (var span in clone.SelectNodes("span"))
        clone.RemoveChild(span);
    foreach (var div in clone.SelectNodes("div[not(@class='contenu')]"))
        clone.RemoveChild(div);
    // remove other nodes which you want to skip here
    string innerTextOfP = Regex.Replace(clone.InnerText, @"'s+", " ");
}

请注意,我使用正则表达式将几个连续的空格替换为一个空格。输出为:

这里又有一些东西,但我们保留这个我们很好 现在就去