使用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>
有帮助吗?

解决方案

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

假设我们已经定义了 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. X Path
或者我们可以使用 XPATH.

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

Console.WriteLine(name);
//John

其他提示

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字符串显然必须在低速案例中。

编辑:显然,Beta现在直接支持LINQ到对象,因此可能不需要转换器。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top