I'm trying to create a code snippet to remove all style attributes regardless of tag using HtmlAgilityPack.
Here's my code:
var elements = htmlDoc.DocumentNode.SelectNodes("//*"); if (elements!=null) { foreach (var element in elements) { element.Attributes.Remove("style"); } } However, I'm not getting it to stick? If I look at the element object immediately after Remove("style"). I can see that the style attribute has been removed, but it still appears in the DocumentNode object. :/
I'm feeling a bit stupid, but it seems off to me? Anyone done this using HtmlAgilityPack? Thanks!
Update
I changed my code to the following, and it works properly:
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 style='style1'><body style='style2'></body></html>and it works