使用HtmlAgilityPack删除属性

26

我正在尝试使用HtmlAgilityPack创建一个代码段,以便移除所有带有style属性的标签。

这是我的代码:

var elements = htmlDoc.DocumentNode.SelectNodes("//*");

if (elements!=null)
{
    foreach (var element in elements)
    {
        element.Attributes.Remove("style");
    }
}

然而,我不能让它生效。如果我在 Remove("style") 后立即查看 element 对象,我会发现 style 属性已被移除,但它仍然出现在 DocumentNode 对象中。:/

我感觉有点蠢,但这对我来说似乎不太对?有人使用 HtmlAgilityPack 做过类似的事情吗?谢谢!

更新

我将代码更改为以下内容,它可以正常工作:

public static void RemoveStyleAttributes(this HtmlDocument html)
{
   var elementsWithStyleAttribute = html.DocumentNode.SelectNodes("//@style");

   if (elementsWithStyleAttribute!=null)
   {
      foreach (var element in elementsWithStyleAttribute)
      {
         element.Attributes["style"].Remove();
      }
   }
}

你能添加一个复现代码吗?因为我已经测试了这个HTML <html style='style1'><body style='style2'></body></html>,它可以工作。 - Simon Mourier
你使用 InnerHtml 属性吗?在撰写本文时,它存在一个 bug,请改用 WriteContentTo 方法。 - greenoldman
2个回答

10

您的代码片段似乎是正确的-它删除了属性。问题在于,DocumentNode .InnerHtml(我假设您监视了此属性)是一个复杂的属性,可能会在某些未知情况下更新,实际上您不应该使用此属性获取文档字符串。而是应该使用 HtmlDocument.Save 方法:

string result = null;
using (StringWriter writer = new StringWriter())
{
    htmlDoc.Save(writer);
    result = writer.ToString();
}
现在result变量包含您文档的字符串表示形式。
还有一件事:通过将表达式更改为"//*[@style]",可以改进您的代码,这将使您仅获取具有style属性的元素。

谢谢您的回复!是的,我把我的代码改为以下内容,以使其“固定”:'public static void RemoveStyleAttributes(this HtmlDocument html) { var elementsWithStyleAttribute = html.DocumentNode.SelectNodes("//@style"); if (elementsWithStyleAttribute!=null) { foreach (var element in elementsWithStyleAttribute) { element.Attributes["style"].Remove(); } } }'不确定为什么我的原始代码没有起作用,但我认为你的猜测是正确的。谢谢! - Ted Nyberg
哇,注释中的代码格式不太好。 :) 我已经更新了我的问题,并附上了修改后的代码片段。再次感谢! - Ted Nyberg

9

这里有一个非常简单的解决方案

VB.net

element.Attributes.Remove(element.Attributes("style"))

c#

element.Attributes.Remove(element.Attributes["style"])

2
谢谢,有一个更正:element.Attributes("style") 应该是 element.Attributes["style"]。 - Patrick Koorevaar
1
你说得对,因为我没有表达清楚:我的代码是用VB.NET编写的。 - Otto Kanellis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接