views:

1135

answers:

4

Using C# I would like to know how to get the Textbox value (i.e: john) from this sample html script :

<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>
A: 

This is quite simple, just add the runat and id tags to your input control, then you'll be able to access it in your C# code.

<INPUT class=box runat=server id="name" value=John maxLength=16 size=16 name=user_name>

Then you do this to get the value of it in code:

string name = this.name.Value;

Hope this helps.

Ricardo
I'm not sure this is what the OP wanted to know. He's parsing externally supplied HTML with a well known parser (HtmlAgilityPack).
spender
@spender You are correct! I jumped and wrote my answer too fast, didn't pay attention at the HtmlAgilityPack, never heard of it ;)
Ricardo
+1  A: 
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);
}

I wrote this pretty quickly, so you'll want to do some testing with more data.

NOTE: The XPath strings apparently have to be in lower-case.

EDIT: There's also the Html Agility Pack to LINQ to XML Converter - I haven't tried this one yet.

EDIT: Apparently the beta now supports Linq to Objects directly, so there's probably no need for the converter.

TrueWill
+5  A: 

There are a number of ways to select elements using the agility pack.

Let's assume we have defined our HtmlDocument as follows:

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. Simple LINQ
We could use the Descendants() method, passing the name of an element we are in search of:

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

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

2. More advanced LINQ
We could narrow that down by using fancier 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
Or we could use XPath.

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

Console.WriteLine(name);
//John
Bauer
A: 

Great answer, thank you very much for the info!

Ravenheart