使用HTML Agility Pack删除重复元素链

我正在尝试删除我的html文档中任何重复或更多出现的任何
标记。 这是我到目前为止提出的(非常愚蠢的代码):

HtmlNodeCollection elements = nodeCollection.ElementAt(0) .SelectNodes("//br"); if (elements != null) { foreach (HtmlNode element in elements) { if (element.Name == "br") { bool iterate = true; while(iterate == true) { iterate = removeChainElements(element); } } } } private bool removeChainElements(HtmlNode element) { if (element.NextSibling != null && element.NextSibling.Name == "br") { element.NextSibling.Remove(); } if (element.NextSibling != null && element.NextSibling.Name == "br") return true; else return false; } } 

代码确实找到了br标签,但它根本不删除任何元素。

我认为你的解决方案太复杂了,虽然这个想法似乎是正确的,正如我所理解的那样。

假设,首先找到所有
节点会更容易,只需删除那些以前的兄弟节点是节点的节点。

让我们从下一个例子开始:

 var html = @"
the first line

the next one
"; var doc = new HtmlDocument(); doc.LoadHtml(html);

现在找到
节点并删除重复元素链:

 var nodes = doc.DocumentNode.SelectNodes("//br").ToArray(); foreach (var node in nodes) if (node.PreviousSibling != null && node.PreviousSibling.Name == "br") node.Remove(); 

并得到它的结果:

 var output = doc.DocumentNode.OuterHtml; 

它是:

 
the first line
the next one

也许你可以这样做htmlsource = htmlSource.Replace("

",
);

或者类似的东西

  string html = "




"; html = html.Replace("
", string.Empty); html = string.Format("{0}
", html); html = html.Replace(" ", string.Empty); html = html.Replace("\t", string.Empty);