Kevin Appleyard
Kevin Appleyard

Reputation: 149

Select value from HTML with HTMLAgilityPack

I need some help on how to extract a value from some HTML using the HTML Agility Pack. The (partial) HTML is:

<HTML>
<BODY bgcolor="FFFFFF" onLoad="window.document.forms[0].p_wwwparam.focus();">
<BR>
<DIV ALIGN="CENTER">
<CENTER><U><font color="800040"><H2>Password Reset Form</H2></font></U></CENTER>
<BR>
<TABLE >
<TH ALIGN="CENTER" COLSPAN="2"><FONT COLOR="800040">Verification details for 
</FONT>WSCCD03</TH>
<TR>
<TD>EIN: </TD>
<TD>987654321</TD>
</TR>
<TR>
<TD>Full name: </TD>
<TD>Bob Bobbity</TD>
</TR>
</TABLE>
...... Rest of document

I need to extract the value from the td following the one containing 'EIN:' so in this case I need to extract '987654321'

Any help would be much appreciated.

Upvotes: 1

Views: 346

Answers (3)

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102408

Here's a simple code that will allow you to get the 2nd td value:

var htmlDoc = new HtmlDocument();

// Point to your HTML doc content here... :)
htmlDoc.Load(@"C:\Libs\HtmlAgilityPack.1.4.0\htmldocument.html");

var node = htmlDoc.DocumentNode.SelectNodes("//td").Skip(1).Take(1).Single();

System.Console.WriteLine(node.InnerText);

Upvotes: 0

L.B
L.B

Reputation: 116118

This should work

var text = doc.DocumentNode.SelectSingleNode("//td[text()='EIN: ']/../td[2]")
              .InnerText;

Upvotes: 2

Daniel
Daniel

Reputation: 11054

You could do something like:

HtmlDocument doc = new HtmlWeb().Load("http://www.yoursite.com/yourpage.html");
HtmlNodeCollection trs = doc.DocumentNode.SelectNodes(".//tr");
HtmlNodeCollection tds = trs[0].SelectNodes(".//td");
var text = tds[1].InnerText;

Upvotes: 0

Related Questions