How to select elements using HTML agility pack include selector element?

c# html-agility-pack

Question

How select element by class include this selector? Example:

<div class="bla">
  <p>Some text1</p>
</div>
<div class="bla">
  <p>Some text2</p>
</div>

if use

 html.DocumentNode.SelectNodes("//div[@class='bla']")

then we get only <p>Some Text1</p> and <p>Some text2</p> I need get html include selector element like this

<div class="bla">

<p>Some text</p>

</div>

help)))

Accepted Answer

You can keep using //div[@class='bla'] selector and get HTML markup of the corresponding divs from OuterHtml property, for example :

var html = @"<div>
    <div class='bla'>
      <p>Some text1</p>
    </div>
    <div class='bla'>
      <p>Some text2</p>
    </div>
</div>";
var doc = new HtmlDocument();
doc.LoadHtml(html);

var nodes = doc.DocumentNode.SelectNodes("//div[@class='bla']");
foreach(HtmlNode node in nodes)
{
    Console.WriteLine(node.OuterHtml);
    Console.WriteLine();
}

Dotnetfiddle Demo

output :

<div class='bla'>
      <p>Some text1</p>
    </div>

<div class='bla'>
      <p>Some text2</p>
    </div>



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why