Esistono diversi modi per selezionare gli elementi utilizzando il pacchetto agilità.
Supponiamo che abbiamo definito il nostro HtmlDocument
come segue:
string html = @"<TD class=texte width=""50%"">
<DIV align=right>Name :<B> </B></DIV></TD>
<TD width=""50%"">
<INPUT class=box value=John maxLength=16 size=16 name=user_name>
</TD>
<TR vAlign=center>";
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
1. LINQ semplice
potremmo usare il metodo Descendants()
, passando il nome di un elemento che siamo alla ricerca di:
var inputs = htmlDoc.DocumentNode.Descendants("input");
foreach (var input in inputs)
{
Console.WriteLine(input.Attributes["value"].Value);
// John
}
2. Più LINQ avanzata
Potremmo restringere che verso il basso, utilizzando più elaborato LINQ:
var inputs = from input in htmlDoc.DocumentNode.Descendants("input")
where input.Attributes["class"].Value == "box"
select input;
foreach (var input in inputs)
{
Console.WriteLine(input.Attributes["value"].Value);
// John
}
3. XPath
Oppure potremmo usare XPath.
string name = htmlDoc.DocumentNode
.SelectSingleNode("//td/input")
.Attributes["value"].Value;
Console.WriteLine(name);
//John
LINQ: Nel caso in cui l'attributo non era lì ho usato il seguente LINQ per 'dove input.Attributes [ "classe"] = null && input.Attributes [ "classe"] Valore =="!. box "' –