使用HtmlAgilityPack删除属性
我正在尝试创建一个代码段,以删除所有使用HtmlAgilityPack删除属性,html,html-parsing,html-agility-pack,Html,Html Parsing,Html Agility Pack,我正在尝试创建一个代码段,以删除所有style属性,而不考虑标记的使用 这是我的密码: var elements = htmlDoc.DocumentNode.SelectNodes("//*"); if (elements!=null) { foreach (var element in elements) { element.Attributes.Remove("style"); } } 然而,我没有让它坚持下去?如果我在删除(“样式”)之后立即查
style
属性,而不考虑标记的使用
这是我的密码:
var elements = htmlDoc.DocumentNode.SelectNodes("//*");
if (elements!=null)
{
foreach (var element in elements)
{
element.Attributes.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();
}
}
}
您的代码片段似乎是正确的-它删除了属性。问题是,
DocumentNode.InnerHtml
(我假设您监控了这个属性)是一个复杂的属性,可能在一些未知的情况下它会被更新,您实际上不应该使用这个属性来获取作为字符串的文档。而不是HtmlDocument.Save
方法:
string result = null;
using (StringWriter writer = new StringWriter())
{
htmlDoc.Save(writer);
result = writer.ToString();
}
现在result
变量保存文档的字符串表示形式
还有一件事:通过将表达式更改为
“/*[@style]”
,您的代码可能会得到改进,这将只获得具有style
属性的元素。下面是一个非常简单的解决方案
VB.net
element.Attributes.Remove(element.Attributes("style"))
c#
你能添加复制代码吗?因为我已经测试了这个html
并且它可以工作,所以您是否使用InnerHtml属性?在写这篇文章的时候,它有一个bug,使用WriteContentTo方法代替。谢谢回复!是的,我已将代码更改为以下内容以使其“保持不变”:“public static void RemoveStyleAttributes(this HtmlDocument html){var elementsWithStyleAttribute=html.DocumentNode.SelectNodes(“/@style”);if(elementsWithStyleAttribute!=null){foreach(elementsWithStyleAttribute中的var元素){element.Attributes[“style”].Remove();}}}}}不确定我的原始代码为什么不起作用,但我认为你的猜测是对的。谢谢!哇,注释中的代码格式不太好。:)用修改过的代码片段更新了我的问题。再次感谢!谢谢,一个更正:element.Attributes(“style”)应该是element.Attributes[“style”]你是对的,因为我没有说清楚:我的代码是为vb.net编写的
element.Attributes.Remove(element.Attributes["style"])