我们有一个非常庞大的帮助文档,是在Word中创建的,并用它生成了一个更加庞大和难以操作的HTML文档。使用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>
从逻辑上讲,有一个带有部分名称的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);
由于我找不到相关文档,我不知道如何从起始节点到达下一个 h1 元素。如果有建议,请告诉我,谢谢。
HtmlNode startNode = helpDocument.DocumentNode.Descendants("h1").Where(d => d.InnerText.Contains(SectionName)).FirstOrDefault();
并从那里向上移动到父节点。其余部分完美地运行了。谢谢。 - Rondel