Using HtmlAgilityPack, remove attributes.

html html-agility-pack html-parsing


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)

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!


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)
8/5/2014 7:28:27 PM

Accepted Answer

Your code snippet seems to be correct - it removes the attributes. The thing is, DocumentNode .InnerHtml(I assume you monitored this property) is a complex property, maybe it get updated after some unknown circumstances and you actually shouldn't use this property to get the document as a string. Instead of it HtmlDocument.Save method for this:

string result = null;
using (StringWriter writer = new StringWriter())
    result = writer.ToString();

now result variable holds the string representation of your document.

One more thing: your code may be improved by changing your expression to "//*[@style]" which gets you only elements with style attribute.

5/6/2011 1:49:52 PM

Popular Answer

Here is a very simple solution




Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow