我正在尝试创建一个代码段来删除所有样式属性,而不管标签使用
HtmlAgilityPack.
这是我的代码:
var elements = htmlDoc.DocumentNode.SelectNodes("//*"); if (elements!=null) { foreach (var element in elements) { element.Attributes.Remove("style"); } }
但是,我没有得到它坚持?如果我在Remove(“style”)后立即查看元素对象.我可以看到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(); } } }
解决方法
@H_301_19@ 您的代码片段似乎是正确的 – 它会删除属性.事情是,DocumentNode .InnerHtml(我认为你监视这个属性)是一个复杂的属性,也许它在一些未知的情况下得到更新,实际上不应该使用此属性来获取文档作为一个字符串.而不是它的HtmlDocument.Save方法为此:string result = null; using (StringWriter writer = new StringWriter()) { htmlDoc.Save(writer); result = writer.ToString(); }
现在result变量保存文档的字符串表示形式.