我試圖用HtmlAgilityPack刪除空的html節點。我想刪除所有節點是這樣的:如何用HtmlAgilityPack刪除空html節點?
<p><span> </span></p>
這裏就是我想,但它不工作:你可以這樣做
static string RemoveEmptyParagraphs(string html)
{
HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(html);
foreach (HtmlNode eachNode in document.DocumentNode.SelectNodes("//p/span/text() = ' '"))
eachNode.Remove();
html = document.DocumentNode.OuterHtml;
return html;
}
兩件事。首先,如果你想刪除任何節點,你不能使用'foreach',而是使用'for'循環,因爲這是從列表中刪除項目的唯一正確方法。其次,嘗試將XPath字符串改爲'「// p/span [text()=' ']」'或'「// p/span [contains(text()=' ')]''if you期望任何空格在源HTML中出現。 – LightBulb 2015-03-25 10:56:16
感謝LightBulb,我的xpath是一團糟,糾正了xpath。 – bearaman 2015-03-25 15:20:36