J'ai besoin d'identifier la classe d'un élément div
qui contient du texte. Par exemple j'ai cette page HTML
<html>
...
<div class='x'>
<p>this is the text I have.</p>
<p>Another part of text.</p>
</div>
...
</html>
Donc, je connais le texte, this is the text I have. Another part of text.
Et je dois identifier le nom de la classe div. Y a-t-il un moyen de faire cela en utilisant C #?
Construire sur la réponse de diiN_. C'est un peu bavard, mais vous devriez pouvoir obtenir ce dont vous avez besoin. Le code dépend du HTML Agility Pack . Vous pouvez l'obtenir en utilisant une pépite.
var sb = new StringBuilder();
sb.AppendFormat("<html>");
sb.AppendFormat("<div class='x'>");
sb.AppendFormat("<p>this is the text I have.</p>");
sb.AppendFormat("<p>Another part of text.</p>");
sb.AppendFormat("</div>");
sb.AppendFormat("</html>");
const string stringToSearch = "<p>this is the text I have.</p><p>Another part of text.</p>";
var document = new HtmlDocument();
document.LoadHtml(sb.ToString());
var divsWithText = document
.DocumentNode
.Descendants("div")
.Where(node => node.Descendants()
.Any(des => des.NodeType == HtmlNodeType.Text))
.ToList();
var divsWithInnerHtmlMatching =
divsWithText
.Where(div => div.InnerHtml.Equals(stringToSearch))
.ToList();
var innerHtmlAndClass =
divsWithInnerHtmlMatching
.Select(div =>
new
{
InnerHtml = div.InnerHtml,
Class = div.Attributes["class"].Value
});
foreach (var item in innerHtmlAndClass)
{
Console.WriteLine("class='{0}' innerHtml='{1}'", item.Class, item.InnerHtml);
}
Essaye ça:
string stringToSearch = "<p>this is the text I have.</p><p>Another part of text.</p>";
HtmlDocument document = new HtmlDocument();
document.LoadHtml(sb.ToString());
var classOfDiv = document.DocumentNode.Descendants("div").Select(x => new
{
ClassOfDiv = x.Attributes["class"].Value
}).Where(x => x.InnerHtml = stringToSearch);
La variable classOfDiv
contient maintenant le nom de la class
du div
désiré.