HTML敏捷包 - 而不删除内容除去不需要的标签? [英] HTML agility pack - removing unwanted tags without removing content?
问题描述
我已经看到了一些相关的问题在这里,但它们不rsquo的;第•正是说说我面临同样的问题。
I've seen a few related questions out here, but they don’t exactly talk about the same problem I am facing.
我想使用 HTML敏捷性包,向我的HTML中删除不需要的标签没有松动的标签中的内容。
I want to use the HTML Agility Pack to remove unwanted tags from my HTML without loosing the content within the tags.
因此,举例来说,在我的情况,我想preserve标签 B
, I
和 U
So for instance, in my scenario, I would like to preserve the tags "b
", "i
" and "u
".
和一个输入,如:
< P>我的款< DIV>和我的< B> DIV< / B>< / DIV>是< I>斜体< / I>和< B>大胆< / B>< / P>
产生的HTML应该是:
The resulting HTML should be:
我的款,我的< B> DIV< / B>是< I>斜体< / I>和< B>大胆< / B>
我试着用 HtmlNode
的删除
方法,但它也删除我的内容。有什么建议?
I tried using HtmlNode
's Remove
method, but it removes my content too. Any suggestions?
推荐答案
我写了基于俄德的建议的算法。这里是。就像一个魅力。
I wrote an algorithm based on Oded's suggestions. Here it is. Works like a charm.
它会删除所有的标签,除了强烈
, EM
, U
和原始文本节点。
It removes all tags except strong
, em
, u
and raw text nodes.
internal static string RemoveUnwantedTags(string data)
{
var document = new HtmlDocument();
document.LoadHtml(data);
var acceptableTags = new String[] { "strong", "em", "u"};
var nodes = new Queue<HtmlNode>(document.DocumentNode.SelectNodes("./*|./text()"));
while(nodes.Count > 0)
{
var node = nodes.Dequeue();
var parentNode = node.ParentNode;
if(!acceptableTags.Contains(node.Name) && node.Name != "#text")
{
var childNodes = node.SelectNodes("./*|./text()");
if (childNodes != null)
{
foreach (var child in childNodes)
{
nodes.Enqueue(child);
parentNode.InsertBefore(child, node);
}
}
parentNode.RemoveChild(node);
}
}
return document.DocumentNode.InnerHtml;
}
这篇关于HTML敏捷包 - 而不删除内容除去不需要的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!