【问题标题】:Remove attributes using HtmlAgilityPack使用 HtmlAgilityPack 删除属性
【发布时间】:2011-08-16 13:57:50
【问题描述】:

我正在尝试创建一个代码 sn-p 以删除所有 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();
      }
   }
}

【问题讨论】:

  • 可以加复制码吗?因为我已经测试过这个 html <html style='style1'><body style='style2'></body></html> 并且它有效
  • 你使用 InnerHtml 属性吗?在撰写本文时,它有一个错误,请改用 WriteContentTo 方法。

标签: html html-parsing html-agility-pack


【解决方案1】:

您的代码 sn-p 似乎是正确的 - 它删除了属性。问题是,DocumentNode .InnerHtml(我假设你监视了这个属性)是一个复杂的属性,它可能会在一些未知的情况下被更新,你实际上不应该使用这个属性来获取文件作为字符串。取而代之的是 HtmlDocument.Save 方法:

string result = null;
using (StringWriter writer = new StringWriter())
{
    htmlDoc.Save(writer);
    result = writer.ToString();
}

现在result 变量保存了文档的字符串表示形式。

还有一件事:可以通过将表达式更改为 "//*[@style]" 来改进您的代码,这只会让您获得具有 style 属性的元素。

【讨论】:

  • 感谢您的回复!是的,我已将代码更改为以下内容以使其“粘贴”:'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(); } } }' 不知道为什么我的原始代码不起作用,但我认为你的猜测是正确的。谢谢!
  • 哇,cmets 中的代码格式不是很好。 :) 用修改后的代码 sn-p 更新了我的问题。再次感谢!
【解决方案2】:

这是一个非常简单的解决方案

VB.net

element.Attributes.Remove(element.Attributes("style"))

c#

element.Attributes.Remove(element.Attributes["style"])

【讨论】:

  • 谢谢,更正一点:element.Attributes("style") 应该是 element.Attributes["style"]
  • 你是对的,因为我没有说清楚:我的代码是用于 vb.net
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-28
  • 1970-01-01
  • 2014-05-31
  • 2021-12-23
相关资源
最近更新 更多