使用 Html Agility Pack 获取两个 HTML 标记之间的内容

本文关键字:HTML 之间 两个 Pack Agility Html 获取 使用 | 更新日期: 2023-09-27 18:35:45

我们在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>

从逻辑上讲,a标签中有一个带有节名的H1。我想从包含div 的外部选择所有内容,直到遇到另一个h1并排除该div。

  • 每个部分名称都位于h1下的<a>标记中,该有多个子项(每个子项约 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 元素。任何建议将不胜感激。

使用 Html Agility Pack 获取两个 HTML 标记之间的内容

我认为这会做到,尽管它假设 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;
}

那么,你真正想要的是h1-Tag周围的div?如果是,那么这应该有效。

helpDocument.DocumentNode.SelectSingleNode("//h1/a[contains(@name, '"+sectionName+"')]/ancestor::div");

也可以根据您的 HTML 处理SelectNodes。喜欢这个:

helpDocument.DocumentNode.SelectNodes("//h1/a[starts-with(@name,'_Toc')]/ancestor::div");

哦,在测试这个时,我注意到对我不起作用的是包含方法中的点,一旦我将其更改为 name 属性,一切正常。