我正在尝试创建一个代码片段来删除所有 style
属性,而不考虑使用 HtmlAgilityPack 的标签.
这是我的代码:
var elements = htmlDoc.DocumentNode.SelectNodes("//*");
if (elements!=null)
{
foreach (var element in elements)
{
element.Attributes.Remove("style");
}
}
但是,我无法坚持下去?如果我在 Remove("style")
之后立即查看 element
对象。我可以看到样式属性已被删除,但它仍然出现在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
属性的元素。
关于html - 使用 HtmlAgilityPack 删除属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5850718/