使用HtmlAgilityPack从标记节点中删除类名

时间:2014-09-02 10:51:17

标签: c# html xpath html-agility-pack

我需要从html中删除特定的类名,例如:

<table class="removeme"></table>

我需要一个可以删除指定类的代码剪切&#34; removeme&#34;和清洁后的HTML将如下所示:

<table></table>

还要记住,传递的html可以包含类似的内容:

<table class="removeme leaveme"></table>

清洁后应显示为:

<table class="leaveme"></table>

1 个答案:

答案 0 :(得分:2)

您可以尝试分两步解决这个问题,首先让所有节点只有'removeme`类属性,然后从中删除整个类属性:

//*[normalize-space(@class)='removeme']

然后在下一步中,获取具有removeme类和其他一些类的所有节点,然后从类属性中删除removeme

//*[
     normalize-space(@class)!='removeme'
        and
     contains(concat(' ', normalize-space(@class), ' '), ' removeme ')
   ]

上面XPath中的第一个条件意味着获取步骤1中未处理的所有节点,第二个条件为the equivalent XPath for css selector .removeme

以下是完整的控制台示例:

var xml = @"<root>
    <table class=""removeme""></table>
    <table class=""removeme leaveme""></table>
    <table class="" removeme ""></table>
</root>";
var doc = new HtmlDocument();
doc.LoadHtml(xml);
var removemeOnly = doc.DocumentNode.SelectNodes("//*[normalize-space(@class)='removeme']");
foreach (HtmlNode node in removemeOnly)
{
    node.Attributes["class"].Remove();
}
var containsRemoveme =
    doc.DocumentNode.SelectNodes("//*[normalize-space(@class)!='removeme' and contains(concat(' ', normalize-space(@class), ' '), ' removeme ')]");
foreach (HtmlNode node in containsRemoveme)
{
    node.Attributes["class"].Value = node.Attributes["class"].Value.Replace("removeme", "");
}
//print formatted HTML output (don't use this for non XML-compliant HTML)
Console.WriteLine(XDocument.Parse(doc.DocumentNode.OuterHtml));