35

使用 C# 我想知道如何从这个示例 html 脚本中获取文本框值(即:john):

<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>
4

2 回答 2

51

有多种方法可以使用敏捷包选择元素。

假设我们已经定义HtmlDocument如下:

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
我们可以使用该Descendants()方法,传递我们要搜索的元素的名称:

var inputs = htmlDoc.DocumentNode.Descendants("input");

foreach (var input in inputs)
{
    Console.WriteLine(input.Attributes["value"].Value);
    // John
}

2. 更高级的 LINQ
我们可以通过使用更高级的 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
或者我们可以使用XPath

string name = htmlDoc.DocumentNode
    .SelectSingleNode("//td/input")
    .Attributes["value"].Value;

Console.WriteLine(name);
//John
于 2009-10-03T02:35:54.650 回答
2
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
XPathNavigator docNav = doc.CreateNavigator();

XPathNavigator node = docNav.SelectSingleNode("//td/input/@value");

if (node != null)
{
    Console.WriteLine("result: " + node.Value);
}

我写得很快,所以你会想用更多的数据做一些测试。

注意:XPath 字符串显然必须是小写的。

编辑:显然测试版现在直接支持 Linq to Objects,所以可能不需要转换器。

于 2009-10-03T02:30:06.857 回答