Devo identificare la classe di un elemento div
che contiene del testo. Ad esempio ho questa pagina HTML
<html>
...
<div class='x'>
<p>this is the text I have.</p>
<p>Another part of text.</p>
</div>
...
</html>
Quindi conosco il testo this is the text I have. Another part of text.
E ho bisogno di identificare il nome della classe div. C'è un modo per farlo usando C #?
Basandosi sulla risposta di diiN_. Questo è un po 'prolisso ma dovresti essere in grado di ottenere ciò di cui hai bisogno. Il codice dipende da HTML Agility Pack . Puoi ottenerlo usando Nuget.
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);
}
Prova questo:
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 variabile classOfDiv
ora contiene il nome della class
del div
desiderato.