HAP - Request - Get nodes between comments

CSharp · Console

/Program.cs

// @nuget: HtmlAgilityPack

using System;
using System.Linq;

public class Program
{
	public static void Main()
	{
  var html = @"
<body>
    <p>Title 
    </p>
    <!-- data-example-start-try_1 -->
    <div>
    </div>
    <span id=""hello""> Hi
    </span>
    <!-- data-example-end-try_1 -->
    <!-- data-example-start-goodbye 2-->
    <div> 
    <span id=""bye""> Bye
    </span>
    </div>
    <p>
    </p>
    <!-- data-example-end-goodbye 2-->
</body>
             ";

		var doc = new HtmlAgilityPack.HtmlDocument();
		doc.LoadHtml(html);
		var docNode = doc.DocumentNode.InnerHtml;

		var descendants = doc.DocumentNode.Descendants().ToList();

		var startNode = descendants.FindIndex(x => x.InnerHtml == "<!-- data-example-start-try_1 -->");
		var endEnd = descendants.FindIndex(x => x.InnerHtml == "<!-- data-example-end-try_1 -->");

		if (startNode != -1 && endEnd != 1)
		{
			var betweenNodes = descendants.GetRange(startNode + 1, endEnd - startNode - 1);

			foreach (var node in betweenNodes)
			{
				// show 2 times "Hi", once for the span, once for the text
				Console.WriteLine(node.InnerHtml);
			}
		}
	}
}
;