使用 HtmlAgilityPack 从解析的 HTML 中删除所有类和 ID

Ale*_*lex 3 html c# html-agility-pack

我使用HtmlAgilityPack来解析一些 html 页面,我从这个页面中提取 html 标签,如下所示:

HtmlNode bodyContent = document.DocumentNode.SelectSingleNode("//body");
var all_text = bodyContent.SelectNodes("//div | //ul | //p | //table");
Run Code Online (Sandbox Code Playgroud)

在返回的 html 中,每个标签都包含类和 id,我想删除所有 id-s 和所有类,我该怎么做?

Iva*_*vic 5

也许你应该检查这个链接:链接

据我所知,当你拥有 HtmlNode 时,你可以使用它的属性 Attributes。此集合具有方法 Remove(string) 接收要删除的属性名称。嗯,我在一个小项目中是这样使用的。我不确定这是否对你有帮助。

所以基本上:

HtmlNode bodyContent = document.DocumentNode.SelectSingleNode("//body");
var all_text = bodyContent.SelectNodes("//div | //ul | //p | //table");

foreach(var node in all_text)
{
   node.Attributes.Remove("class");
   node.Attributes.Remove("id");
} 
Run Code Online (Sandbox Code Playgroud)