删除两个元素之间的所有元素我有大约2500个不同标准的html文件。我需要删除它们的页脚部分。下面的HTML代码是我的文档页脚之一,我需要删除两个hr元素和它们之间的元素。到目前为止,我只尝试使用xpath(和HTMLAgilityPack)selectSingleNode和DocumentNode.SelectNodes("//hr");定位hr元素;然后尝试使用foreach进行迭代。但是我在XPath上玩得太多了,不知道如何选择一个节点及其兄弟节点(?)来删除它们。这是我在社区的帮助下到目前为止所得到的。?privatestaticvoidRemoveHR(IEnumerablefiles){vardocument=newHtmlDocument();列出hr=newList();列表错误=newList();诠释我=0;foreach(文件中的var文件){try{document.Load(@file);我++;varhrs=document.DocumentNode.SelectNodes("//hr");foreach(varhrinhrs)hr.Remove();文档.保存(@文件);}catch(ExceptionEx){errors.Add(file+"|"+Ex.Message);}}使用(StreamWriterlogger=File.CreateText(@"D:websitesdev.openjournal.tldpublicarkivetErrorLogshr_error_log.txt")){foreach(varfileinerrors){logger.WriteLine(file);}}intnrOfHr=hr.Count();intnrOfErrors=errors.Count();Console.WriteLine("收集到的hr元素个数:{0}",nrOfHr);Console.WriteLine("缺少hr元素的文件数:{0}",nrOfErrors);}HTML代码://startelement如何引用这篇论文:Ekmek?ioglu,F.?una,Lynch,MichaelF.&Willett,Peter(1996)"StemmingandN-grammatchingfortermconflationinTurkishtexts"InformationResearch,1(1)位于:http://informationr.net/ir/2-2/paper13.html?theauthors,1996.检查引用,使用GoogleScholarContentsWebCountingonlysince13December2002Home//endelementEdit我用previous-sibling和follow-sibling对目标节点做了一些实验不幸的是,它不包括列表中的目标节点。varfooterTags=document.DocumentNode.SelectNodes("//*[preceding-sibling::p[contains(text(),'Howtocitethis')]andfollowing-sibling::hr[@color='#ff00ff']]");它找到“,然后选择所有它之间的节点并选择颜色为“ff00ff”的hr。但列表中实际选中的要删除的节点不包括在内,需要连同选中的节点一起删除。假设开始节点和结束节点确实相同(相同的标签名称、属性和属性值),正如您在上面的评论中提到的,这并不难:选择开始节点。迭代并删除每个sibling,包括结束节点。删除起始节点。示例HTML:varhtml=@"DONOTDELETE//startelement如何引用这篇论文:Ekmek?ioglu,F.?una,Lynch,MichaelF.&Willett,Peter(1996)"StemmingandN-grammatchingfortermconflationinTurkishtexts"InformationResearch,1(1)位于:http://informationr.net/ir/2-2/paper13.html?theauthors,1996.检查引文,使用GoogleScholarContentsWebCounterCountingonlysinceDecember132002Home//结束元素不要删除";解析:vardocument=newHtmlDocument();文档.LoadHtml(html);varstartNode=document.DocumentNode.SelectSingleNode("//hr[@size='3'][@color='#ff00ff']");//考虑HTML源代码中不匹配的引号varquotesRegex=newRegex("["']");varstartNodeNoQuotes=quotesRegex.Replace(startNode.OuterHtml,"");HtmlNodesiblingNode;while((siblingNode=startNode.NextSibling)!=null){siblingNode.Remove();if(quotesRegex.Replace(siblingNode.OuterHtml,"")==startNodeNoQuotes){中断;//结束节点}}startNode.Remove();结果输出:DONOTDELETE//endelementDONOTDELETE我想,你期待这个,代码stringcontent=System.IO.File.ReadAllText(@"D:NewTextDocument.txt");stringhtml=Regex.Replace(content,"","",RegexOptions.Singleline);以上就是C#学习教程:删除两个元素之间的所有元素共享如果对你有用,还需要进一步了解C#学习教程,希望大家多多关注——//startelement如何引用本文论文:Ekmek?ioglu,F.?una,Lynch,MichaelF.&Willett,Peter(1996)“土耳其语文本中术语合并的词干匹配和N-gram匹配”信息研究,1(1)可在:http://informationr.net/ir/2-2/paper13.html?theauthors,1996.检查引用,使用GoogleScholarContentsWebCounterCountingonlysince13December2002Home//endelement
