find all elements with data - attribute using html-agility-pack

c# html-agility-pack

Question

I am using Html-agility-Pack to parse an Html block of text. Is it possible to find a list of all elements by their attributes / attribute values ?

for an example, below is a sample html text. using Html-agility-pack how do I find all the elements that has the "data-glossaryid" attribute?

<p> sample text <a href="" data-glossaryid="F776EB48BD"></a>
<p><img  alt="my pic" src="/~/media/Images/mypic.jpg" /></p>
sample text 
<a  href="" data-glossaryid="5D476EB49E"></a>
<p>  more sample text  </p>
<span data-glossaryid="F776EB49EF"> </span>

Accepted Answer

// the html block of text to parse
var a = @"<p> sample text <a href="""" data-glossaryid=""F776EB48BD""></a>
<p><img  alt=""my pic"" src=""/~/media/Images/mypic.jpg"" /></p>
sample text <a  href="""" data-glossaryid=""5D476EB49E""></a>
<p>  more sample text  </p>
<span data-glossaryid=""F776EB49EF""> </span>";

// create an HtmlDocument
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(a);

// get all elements with the attr data-glossaryid and prints its values
foreach (var item in htmlDocument.DocumentNode.SelectNodes("//*[@data-glossaryid]"))
    Console.WriteLine(item.GetAttributeValue("data-glossaryid", ""));



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