Ho del codice HTML che sto analizzando usando C #
Il testo di esempio è sotto, anche se questo viene ripetuto circa 150 volte con record diversi
<strong>Title</strong>: Mr<br>
<strong>First name</strong>: Fake<br>
<strong>Surname</strong>: Guy<br>
Sto cercando di ottenere il testo in un array che sarà come
customerArray [0,0] = Title
customerArray [0,1] = Mr
customerArray [1,0] = First Name
customerArray [1,1] = Fake
customerArray [2,0] = Surname
customerArray [2,1] = Guy
Posso ottenere il testo nell'array ma sto avendo problemi a recuperare il testo dopo la scheda di chiusura FORTE fino al tag BR, quindi a trovare il prossimo tag STRONG
Qualsiasi aiuto sarebbe apprezzato
È possibile utilizzare XPath follow following-sibling::text()[1]
per ottenere il nodo di testo situato direttamente dopo ciascun strong
. Ecco un esempio minimo ma completo:
var raw = @"<div>
<strong>Title</strong>: Mr<br>
<strong>First name</strong>: Fake<br>
<strong>Surname</strong>: Guy<br>
</div>";
var doc = new HtmlDocument();
doc.LoadHtml(raw);
foreach(HtmlNode node in doc.DocumentNode.SelectNodes("//strong"))
{
var val = node.SelectSingleNode("following-sibling::text()[1]");
Console.WriteLine(node.InnerText + ", " + val.InnerText);
}
produzione :
Title, : Mr
First name, : Fake
Surname, : Guy
Dovresti essere in grado di rimuovere ":" eseguendo una semplice manipolazione delle stringhe, se necessario ...
<strong>
è un tag comune, quindi qualcosa di specifico per il formato di esempio che hai fornito.
var html = @"
<div>
<strong>First name</strong><em>italic</em>: Fake<br>
<strong>Bold</strong> <a href='#'>hyperlink</a><br>.
<strong>bold</strong>
<strong>bold</strong> <br>
text
</div>
<div>
<strong>Title</strong>: Mr<BR>
<strong>First name</strong>: Fake<br>
<strong>Surname</strong>: Guy<br>
</div>";
var document = new HtmlDocument();
document.LoadHtml(html);
// 1. <strong>
var strong = document.DocumentNode.SelectNodes("//strong");
if (strong != null)
{
foreach (var node in strong.Where(
// 2. followed by non-empty text node
x => x.NextSibling is HtmlTextNode
&& !string.IsNullOrEmpty(x.NextSibling.InnerText.Trim())
// 3. followed by <br>
&& x.NextSibling.NextSibling is HtmlNode
&& x.NextSibling.NextSibling.Name.ToLower() == "br"))
{
Console.WriteLine("{0} {1}", node.InnerText, node.NextSibling.InnerText);
}
}