Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can any one help me out how to get the CSS Class name or Style properties of a Text / Keyword from html document using C#?
Say I am passing the text "Sample Text" from code.
I have a html document which has following code

<div class="sampleclass">
Sample Text
</div>


I need to get the result as sampleclass when Sample Text is passed.

What I have tried:

I have used HTMLAgility library , I can get the text based on class name but I need the other way around to get class name when text is passed.
Posted
Updated 9-Jan-17 7:56am

1 solution

If you have a HtmlDocument (using HtmlAgilityPack), you can use .DocumentNode.Descendants() to get all descendants, and using the LINQ extension methods, you can search for the element containing 'Sample Text' and get its class:
C#
string html = @"<!DOCTYPE html>
<html>
<head><title>Sample document</title></head>
<body>
<div class=""sampleclass"">
Sample Text
</div>
</body>
</html>";

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);

HtmlNode foundNode = doc.DocumentNode.Descendants().Where(x => x.InnerHtml.Trim() == "Sample Text").FirstOrDefault();
string classAttribute = foundNode?.Attributes["class"]?.Value;
.Where[^] filters the descendants using the predicate x => x.InnerHtml.Trim() == "Sample Text", which means that for an element 'x' in the list of descendants, the trimmed InnerHTML of 'x' must be "Sample Text". .FirstOrDefault[^] returns the first found element, or null if no element is found.

When the node is found, the attribute is fetched from the node. Note that I used ?. instead of just . because ?. is a null-conditional operator[^]. foundNode?.Attributes["class"] means "if foundNode is null, then this expression evaluates to null; if foundNode is not null, then this expression executes .Attributes["class"]". ?.Value works in the same way. Using this operator avoids a few null checks. If foundNode is null or if it doesn't have a class attribute, then classAttribute is null too.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900