1
votes

I'm using Html Agility Pack for build a library with different functionalities.

One of them is:

  • search into HTML all the HTML parts contained between "start comment tag" and "end comment tag"
  • replace all HTML for the HTML part that matches one search string

For example:

  • I need to search HTML parts contained between <!-- data-example-start start tag and <!-- data-example-end end tag. Both are keyword (comments starts with those keywords)
  • The HTML part to replace is the one that contains the keyword "hello"

<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>

In this case I expect to replace the first HTML part contained between <!-- data-example-start-try_1 --> and <!-- data-example-end-try_1 -->, because inside there is the Search Word "hello" that I'm searching for.

How can I select, into Html Agility Pack , HTML parts contained between two HTML comments?

Thanks in advance

1

1 Answers

0
votes

Here is an online example that shows how to get nodes between comment:

https://dotnetfiddle.net/JlkMot

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);
    }
}