Istnieje kilka sposobów wybierania elementów za pomocą pakietu agility.
Załóżmy, że zdefiniowaliśmy nasz HtmlDocument
następująco:
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. Proste LINQ
Mogliśmy użyć metody Descendants()
, przekazując nazwę elementu jesteśmy w poszukiwaniu:
var inputs = htmlDoc.DocumentNode.Descendants("input");
foreach (var input in inputs)
{
Console.WriteLine(input.Attributes["value"].Value);
// John
}
2. Bardziej zaawansowane LINQ
Mogliśmy wąskie, że w dół za pomocą hodowcy 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
Albo możemy użyć XPath.
string name = htmlDoc.DocumentNode
.SelectSingleNode("//td/input")
.Attributes["value"].Value;
Console.WriteLine(name);
//John
LINQ: W przypadku, gdy atrybut nie było tam użyłem następujące LINQ dla Gdzież input.Attributes [ "klasa"] = null && input.Attributes [ "klasa"] Wartość == "!. pole "' –