Ron*_*del 5 .net c# html-agility-pack
我们在Word中创建了一个绝对庞大的帮助文档,这个文档用于生成更大规模且非常复杂的HTM文档.使用C#和这个库,我想只在我的应用程序中的任何一点抓取并显示该文件的一部分.部分分为这样:
<!--logical section starts here -->
<div>
<h1><span style='mso-spacerun:yes'></span><a name="_Toc325456104">Section A</a></h1>
</div>
<div> Lots of unnecessary markup for simple formatting... </div>
.....
<!--logical section ends here -->
<div>
<h1><span style='mso-spacerun:yes'></span><a name="_Toc325456104">Section B</a></h1>
</div>
Run Code Online (Sandbox Code Playgroud)
从逻辑上讲,标签中H1有一个部分名称a.我想从外部包含div中选择所有内容,直到我遇到另一个h1并排除该div.
<a>标签下面,h1该标签有多个孩子(每个约6个)我的尝试:
var startNode = helpDocument.DocumentNode.SelectSingleNode("//h1/a[contains(., '"+sectionName+"')]");
//go up one level from the a node to the h1 element
startNode=startNode.ParentNode;
//get the start index as the index of the div containing the h1 element
int startNodeIndex = startNode.ParentNode.ChildNodes.IndexOf(startNode);
//here I am not sure how to get the endNode location.
var endNode =?;
int endNodeIndex = endNode.ParentNode.ChildNodes.IndexOf(endNode);
//select everything from the start index to the end index
var nodes = startNode.ParentNode.ChildNodes.Where((n, index) => index >= startNodeIndex && index <= endNodeIndex).Select(n => n);
Run Code Online (Sandbox Code Playgroud)
我无法找到关于此的文档,我不知道如何从我的起始节点到下一个h1元素.任何建议,将不胜感激.
我想这会做到这一点,虽然它假设H1标签只出现在节头中.如果不是这种情况,您可以在后代上添加Where以检查它找到的任何H1节点上的其他过滤器.请注意,这将包括它找到的div的所有兄弟节点,直到它到达具有节名称的下一个兄弟节点.
private List<HtmlNode> GetSection(HtmlDocument helpDocument, string SectionName)
{
HtmlNode startNode = helpDocument.DocumentNode.Descendants("div").Where(d => d.InnerText.Equals(SectionName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
if (startNode == null)
return null; // section not found
List<HtmlNode> section = new List<HtmlNode>();
HtmlNode sibling = startNode.NextSibling;
while (sibling != null && sibling.Descendants("h1").Count() <= 0)
{
section.Add(sibling);
sibling = sibling.NextSibling;
}
return section;
}
Run Code Online (Sandbox Code Playgroud)