如何使用 HTMLAgilityPack 从 HTML 中删除空行?

bea*_*man 3 html c# html-agility-pack

我有一个 HTML 文档,其中包含许多我想删除的不必要的空白行。下面是一个 HTML 示例:

<html>

<head>


</head>

<body>

<h1>Heading</h1>

<p>Testing
Run Code Online (Sandbox Code Playgroud)

我已经尝试了以下代码,但它删除了每个换行符,我只想删除那些空行。

static string RemoveLineReturns(string html)
    {
        html = html.Replace(Environment.NewLine, "");
        return html;
    }
Run Code Online (Sandbox Code Playgroud)

知道如何使用 HTMLAgilityPack 做到这一点吗?谢谢,J。

har*_*r07 5

使用 Html Agility Pack 的一种可能方法:

var doc = new HtmlDocument();
//TODO: load your HtmlDocument here

//select all empty (containing white-space(s) only) text nodes :
var xpath = "//text()[not(normalize-space())]";
var emptyNodes = doc.DocumentNode.SelectNodes(xpath);

//replace each and all empty text nodes with single new-line text node
foreach (HtmlNode emptyNode in emptyNodes)
{
    emptyNode.ParentNode
             .ReplaceChild(HtmlTextNode.CreateNode(Environment.NewLine) 
                            , emptyNode
                           );
}
Run Code Online (Sandbox Code Playgroud)