How do I select elements using the HTML Flexibility pack including a selector element?

How do I select an element by the class that this selector includes? Example:

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

      

if used

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

      

then we only get <p>

Some Text1 </p>

and <p>

Some text2 </p>

I need the html to include a selector element like this

<div class="bla">

      

<p>

Some texts </p>

</div>

      

help)))

+3


source to share


1 answer


You can use a selector //div[@class='bla']

and get the HTML markup of the corresponding div

from property OuterHtml

, 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



output:

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

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

      

+1


source







All Articles