Calculate age in Razor(ASP.NET mvc) - c#

I have a View with a table
Here is the code of the View:
#foreach (var item in Model)
{
<tr>
<td class="point">
#(rowNo += 1)
</td>
<td class="FIO" style="text-align: center; font-size: 16px; cursor:pointer">#Html.DisplayFor(modelItem => item.FIO) #Html.Hidden("clientEmail", item.FIO)</td>
<td style="text-align: center; font-size: 16px;">
#Html.DisplayFor(modelItem => item.Email)
</td>
<td style="text-align: center; font-size: 16px;">
#Html.DisplayFor(modelItem => item.City)
</td>
<td style="text-align: center; font-size: 16px;">
#Html.DisplayFor(modelItem => item.Birthday)
</td>
<td style="text-align: center; font-size: 16px;">
#Html.DisplayFor(modelItem => item.Salary)
</td>
<td style="text-align: center; font-size: 16px;">
#Html.DisplayFor(modelItem => item.English)
</td>
<td style="text-align: end;">
<a href='#Url.Action("Edit", "Interwier", new {id = item.Interwier_id})'>
<img src='#Url.Content("~/Images/Edit.png")' />
</a>
<a href='#Url.Action("Delete", "Interwier", new {id = item.Interwier_id})'>
<img src='#Url.Content("~/Images/Delete.png")' />
</a>
</td>
</tr>
}
This code is about Age:
<td style="text-align: center; font-size: 16px;">
#Html.DisplayFor(modelItem => item.Birthday)
</td>
It returns me year from database. I need to show age.
How I can do this correctly?

By your description, your Birthday is a year value you can:
first add a new property in your model used in view for generating Age:
public class ModelName
{
// other properties
// original Birthday property
public int Birthday {get;set;}
// get age by subtracting current year with Birthday year.
public int Aget {get {return DateTime.Now.Year - Birthday;}}
}
then in your view
change displaying Birthday to Age
<td style="text-align: center; font-size: 16px;">
#Html.DisplayFor(modelItem => item.Age)
</td>

Related

How to apply Style Css in mvc foreach loop

I'm new in asp.net mvc and My problem is, I want to conditionally add a CSS background-color to a set of table rows, based on BILL-AMOUNT = 0.00 i have code like this
#model IEnumerable
View
<tbody>
#foreach (var item in Model)
{
<tr>
<td style="padding-left: 12px;">#Html.DisplayFor(modelItem => item.TicketNo)</td>
<td style="padding-left: 12px; display: none;">#Html.DisplayFor(modelItem => item.name)</td>
<td style="padding-left: 12px;">#Html.DisplayFor(modelItem => item.ArrDate)</td>
<td style="padding-left: 12px;">#Html.DisplayFor(modelItem => item.quantity)</td>
<td style="padding-left: 12px;">#Html.DisplayFor(modelItem => item.Total)</td>
<td>#Html.DisplayFor(modelItem => item.Refund)</td>
<td>#Html.DisplayFor(modelItem => item.TotalAmount)</td>
</tr>
}
</tbody>
Assuming you have a class:
.tr-zero {
background-color: #cccccc;
}
You can add the class conditionally like this:
<tr#(item.TotalAmount == 0 ? " class=\"tr-zero\"" : string.Empty)>
<tbody>
#foreach (var item in Model)
{
<tr bgcolor='#(item.AMOUNT==0? "#FFF":"#EEE")'>
<td style="padding-left: 12px;">#Html.DisplayFor(modelItem => item.TicketNo)</td>
<td style="padding-left: 12px; display: none;">#Html.DisplayFor(modelItem => item.name)</td>
<td style="padding-left: 12px;">#Html.DisplayFor(modelItem => item.ArrDate)</td>
<td style="padding-left: 12px;">#Html.DisplayFor(modelItem => item.quantity)</td>
<td style="padding-left: 12px;">#Html.DisplayFor(modelItem => item.Total)</td>
<td>#Html.DisplayFor(modelItem => item.Refund)</td>
<td>#Html.DisplayFor(modelItem => item.TotalAmount)</td>
</tr>
}
<tbody>
#foreach (var item in Model)
{
<tr style="background-color:#(Convert.ToInt32(item.TotalAmount) == 0?"RedColor":"GreenColor")">
<td style="padding-left: 12px;">#Html.DisplayFor(modelItem => item.TicketNo)</td>
<td style="padding-left: 12px; display: none;">#Html.DisplayFor(modelItem => item.name)</td>
<td style="padding-left: 12px;">#Html.DisplayFor(modelItem => item.ArrDate)</td>
<td style="padding-left: 12px;">#Html.DisplayFor(modelItem => item.quantity)</td>
<td style="padding-left: 12px;">#Html.DisplayFor(modelItem => item.Total)</td>
<td>#Html.DisplayFor(modelItem => item.Refund)</td>
<td>#Html.DisplayFor(modelItem => item.TotalAmount)</td>
</tr>
}
</tbody>

Scrollable list

I have table with data that I display at table
Here is Controller
public ActionResult Index()
{
return View(db.Companies.ToList());
}
Here is View
#foreach (var item in Model)
{
<tr>
<td class="point">
#(rowNo += 1)
</td>
<td class="title" style="text-align: center; font-size:20px">
#Html.DisplayFor(modelItem => item.CompanyName)
</td>
<td class="title" style="text-align: center; font-size:20px">
#Html.DisplayFor(modelItem => item.Vacancies.FirstOrDefault().VacancyName)
</td>
<td style="text-align: end;">
<a href='#Url.Action("Edit", "Companies", new {id = item.CompanyID})'>
<img src='#Url.Content("~/Images/Edit.png")'/>
</a>
<a href='#Url.Action("Delete", "Companies", new {id = item.CompanyID})'>
<img src='#Url.Content("~/Images/Delete.png")'/>
</a>
</td>
</tr>
}
Vacancies is Related Data Table to Companies
Company may have 1-10 Vacancies.
How I can show all Vacancies via scrollable list here <td class="title" style="text-align: center; font-size:20px">
#Html.DisplayFor(modelItem => item.Vacancies.FirstOrDefault().VacancyName)
</td>
Assuming that Vacancies is an IEnumerable, or similar collection object (probably is given your use of FirstOrDefault), you could simply iterate them, much the same way you're iterating the Companies list:
#foreach (var item in Model)
{
<tr>
<td class="point">
#(rowNo += 1)
</td>
<td class="title" style="text-align: center; font-size:20px">
#Html.DisplayFor(modelItem => item.CompanyName)
</td>
<td class="title" style="text-align: center; font-size:20px">
<div style="height: 100px; overflow-y: scroll">
#foreach (var vacancy in item.Vacancies)
{
<div>#Html.DisplayFor(v => vacancy.VacancyName)</div>
}
</div>
</td>
<td style="text-align: end;">
<a href='#Url.Action("Edit", "Companies", new {id = item.CompanyID})'>
<img src='#Url.Content("~/Images/Edit.png")'/>
</a>
<a href='#Url.Action("Delete", "Companies", new {id = item.CompanyID})'>
<img src='#Url.Content("~/Images/Delete.png")'/>
</a>
</td>
</tr>
}
On an unrelated note, you could, and arguably should, stick to double quotes for HTML attributes:
<img src="#Url.Content("~/Images/Edit.png")" />

Generate pdf using iTextSharp for different languages

I have tried different options, but it did not work. The code generated pdf for English but does not work for other languages.
using (var ms = new MemoryStream())
{
// Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
var doc = new Document();
{
// Create a writer that's bound to our PDF abstraction and our stream
var writer = PdfWriter.GetInstance(doc, ms);
{
// Open the document for writing
doc.Open();
string finalHtml = string.Empty;
// Read your html by database or file here and store it into finalHtml e.g. a string
// XMLWorker also reads from a TextReader and not directly from a string
using (var srHtml = new StringReader(sHtmlText))
{
// Parse the HTML
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
}
doc.Close();
}
}
// After all of the PDF "stuff" above is done and closed but **before** we
// close the MemoryStream, grab all of the active bytes from the stream
return new PDFFormFillerResult(ms, PDFFormFillerResultType.Success, string.Empty);
//bytes = ms.ToArray();
}
Well we had to buy another 3rd party tool which understands UNICODE characters.
I was able to create multi language PDF in English and Japanese.
The prerequisite for achieving this
1. To have appropriate Font which supports the languages you are planning to use.
2. Implement IFontProvider interface from iTextSharp and register the multi language font you will be using.
If you follow these 2 steps, you can create multi language PDF.
Code Sample:
public class smartUIFontProvider: IFontProvider
{
public Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color)
{
string myFont = #"C:\Tasks\Projects\SampleProject\iTextDemo_PDF\SmartFontUI\SmartFontUI.otf";
iTextSharp.text.pdf.BaseFont bfR;
bfR = iTextSharp.text.pdf.BaseFont.CreateFont(myFont,
iTextSharp.text.pdf.BaseFont.IDENTITY_H,
iTextSharp.text.pdf.BaseFont.EMBEDDED);
iTextSharp.text.BaseColor clrBlack =
new iTextSharp.text.BaseColor(0, 0, 0);
iTextSharp.text.Font fntHead =
new iTextSharp.text.Font(bfR, 12, iTextSharp.text.Font.NORMAL, clrBlack);
return fntHead;
}
public bool IsRegistered(string fontname)
{
return true;
}
}
static void Main (string[] args)
{
// step 1
Document document = new Document();
Byte[] bytes;
var fileName = "resources\\test_" + System.DateTime.Now.ToString("ddMMyyyy_hhmm") + ".pdf";
var testFile = Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), fileName);
MemoryStream ms = new MemoryStream();
// step 2
using (var writer = PdfWriter.GetInstance(document, ms))
{
document.Open();
String example_html = #" <!DOCTYPE html> <html> <head> </head> <body> <h1>Change of Control Application</h1> <br/> <p>Please fill out this form if there are updates to your current organization and its relationship Company has on file with the legal binding entity. Company will review the information and may ask you to provide further information before Company agrees to the requested changes.</p> <br/> <table class='bodyText1LIC general' style='width:700px' id='tblInputForm' > <tr> <td class='bodyText1LIC' colspan='4'> </td> </tr> <tr> <td class='tableBody1' colspan='4'> <h3>Licensee Information</h3> </td> </tr> <tr> <td class='bodyText1SerNo'>1.</td> <td class='bodyText1LIC'>Licensee Name </td> <td valign='top' class='txtboxtd'> 字詰めなどの調整をおすすめします </td> <td> </td> </tr> <tr> <td class='bodyText1LIC' colspan='4'> </td> </tr> <tr> <td class='tableBody1' colspan='4'> <h3>Licensee Primary Contact Information </h3> </td> </tr> <tr> <td class='bodyText1SerNo'>2.</td> <td class='bodyText1LIC'>Name</td> <td class='txtboxtd'> めなどの調整 </td> <td> </td> </tr> <tr> <td class='bodyText1SerNo'>3.</td> <td class='bodyText1LIC'>Job Title</td> <td class='txtboxtd'> T</td> <td> </td> </tr> <tr> <td class='bodyText1SerNo'>4.</td> <td class='bodyText1LIC'>Mailing Address</td> <td class='txtboxtd'>めなどの調整</td> <td> </td> </tr> <tr> <td class='bodyText1SerNo'>5.</td> <td class='bodyText1LIC'>Telephone Number </td> <td class='txtboxtd'>T</td> <td> </td> </tr> <tr> <td class='bodyText1SerNo'>6.</td> <td class='bodyText1LIC'>Email Address </td> <td class='txtboxtd'>abc#test.com</td> <td> </td> </tr> <tr> <td class='bodyText1LIC' colspan='4'> </td> </tr> <tr> <td class='tableBody1' colspan='4'> <h3> Organizational Structure</h3> </td> </tr> <tr> <td class='bodyText1SerNo'> 7.</td> <td class='bodyText1LIC' colspan='3'> Will your Company's Name Change? </td> </tr> <tr> <td></td> <td colspan='3'> Yes</td> </tr> <tr class='nc' id='TrCompanyName'> <td></td> <td class='bodyText1LIC' colspan='2'> a) New company name </td> <td class='txtboxtd'> DSFDASFASDFDSA</td> </tr> <tr class='nc' id='TrEffectiveDate'> <td></td> <td class='bodyText1LIC' colspan='2'> b) Effective Date Company change will take place </td> <td class='txtboxtd'> 04/20/2017</td> </tr> <tr> <td class='bodyText1SerNo'>8.</td> <td class='bodyText1LIC' colspan='3'>Has your Company been Reincorporated or under gone an Internal Reorganization? </td> </tr> <tr> <td></td> <td colspan='3'> No</td> </tr> <tr> <td class='bodyText1LIC' colspan='4'> </td> </tr> <tr> <td class='tableBody1' colspan='4'> <h3>Assets / Stocks to be Acquired </h3> </td> </tr> <tr> <td class='tableBody1' colspan='4'> <h3>Assets to be Acquired</h3> </td> </tr> <tr> <td class='bodyText1SerNo'>9.</td> <td class='bodyText1LIC' colspan='3'>Will some or all of your Company’s Assets be Acquired? </td> </tr> <tr> <td></td> <td colspan='3'> No</td> </tr> <tr> <td class='bodyText1LIC' colspan='4'> </td> </tr> <tr> <td class='tableBody1' colspan='4'> <h3>Stocks to be Acquired </h3> </td> </tr> <tr> <td class='bodyText1SerNo'>10.</td> <td class='bodyText1LIC' colspan='3'>Will some or all of your Company’s Assets be Acquired? </td> </tr> <tr> <td></td> <td colspan='3'> No</td> </tr> <tr> <td class='bodyText1LIC' colspan='4'> </td> </tr> <tr> <td class='tableBody1' colspan='4'> <h3> Effects of Change to Licensee</h3> </td> </tr> <tr> <td class='bodyText1SerNo'> 11.</td> <td class='bodyText1LIC' colspan='3'> Please indicate which Company is the Surviving Legal Entity? </td> </tr> <tr> <td></td> <td class='txtboxtd' colspan='3'> T</td> </tr> <tr> <td class='bodyText1SerNo'>12.</td> <td class='bodyText1LIC' colspan='3'>Please provide the Company that will be the Licensee? </td> </tr> <tr> <td class='txtboxtd'> </td> <td colspan='3'> T</td> </tr> <tr> <td valign='top' class='bodyText1SerNo'>13.</td> <td class='bodyText1LIC' colspan='3'>Will any companies exist to operate as separate Subsidiaries or Affiliates ? </td> </tr> <tr> <td></td> <td colspan='3'> No</td> </tr> <tr> <td class='bodyText1LIC' colspan='4'> </td> </tr> <tr> <td class='tableBody1' colspan='4'> <h3>Existing Agreements</h3> </td> </tr> <tr> <td class='bodyText1SerNo'>14.</td> <td class='bodyText1LIC' colspan='3'>Please identify if any Licenses that will be affected by the Changes described above </td> </tr> <tr> <td></td> <td colspan='3'> No</td> </tr> <tr> <td class='bodyText1LIC' colspan='4'> </td> </tr> <tr> <td class='tableBody1' colspan='4'> <h3>Corporate Documentation</h3> </td> </tr> <tr> <td valign='top' class='bodyText1SerNo'>15.</td> <td class='bodyText1LIC' colspan='3'>Please Select from 1 of the 2 options listed below</td> </tr> <tr> <td></td> <td colspan='3'> Please Describe the Full Legal Structure of this Organization Change in relation to Licensing.</td> </tr> <tr> <td></td> <td colspan='3'> ASDFSDAFDSAFADSFDASF </td> </tr> </table> </body> </html>";
String example_css = #"html { font-family: SmartFontUI; font-size: 14px; } h1, h2, strong { font-family: SmartFontUI; font-weight: bold; display: inline; } h1 { font-size: 18pt; } .main { font-size: 12pt; color: black; font-family: SmartFontUI, Arial, Sans-Serif; background-color: white; text-align: left; line-height: 1.4em; margin: 2%; } .mainDesc { width: 100%; margin: 10px 0; } span { float: left; display: block; width: 100%; margin-bottom: 5px; } .bodyText1SerNo { width: 2em; } .bodyText1LIC { width: 22em; } .txtboxspan { width: 32em; } .tableBody1 { width: 100%; } .nc { margin-left: 100px; } .subtitle { font-size: 16pt; }";
FontFactory.Register(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "SmartFontUI.otf"), "SmartFontUI");
XMLWorkerHelper worker = XMLWorkerHelper.GetInstance();
MemoryStream msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_html));
MemoryStream msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_css));
smartUIFontProvider smartUIFontObj = new smartUIFontProvider();
worker.ParseXHtml(writer, document, msHtml, msCss, System.Text.Encoding.UTF8, smartUIFontObj);
// step 5
document.Close();
}
bytes = ms.ToArray();
System.IO.File.WriteAllBytes(testFile, bytes);
}

How to save necessary information of HTML file to string variable

A HTML file is generated by Android MobileBiz Pro invoice app. I'm trying to make software for print HTML based invoice via receipt printer
I need to save necessary information of HTML file to string variable as mentioned below. I tried using IndexOf method. but it's not working for me. How can I get this information using visual c#?
string subtotal = 2,976.00;
string total = 2,976.00;
string payment= 2,760.00;
string balance= 216.00;
This is an example of the HTML code:
<tr><td align="right" colspan="3">Subtotal</td><td align="right">2,976.00</td></tr><tr><td align="right" colspan="3"><b>TOTAL</b></td><td align="right"><b>2,976.00</b></td></tr><tr><td align="right" colspan="3">Less Payment</td><td align="right">2,760.00</td></tr><tr class="total"><td align="right" colspan="3"><strong>Balance Due</strong></td><td align="right">216.00</td></tr>
This is a complete HTML code of HTML file
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
body {
font-family:Verdana, Geneva, sans-serif;
font-size: 8pt;
padding: 0 50pt 0 50pt;
}
table td, table th, table.sales th, table td.footer-text {
font-size: 8pt;
}
h1 {
font-family:Verdana, Geneva, sans-serif;
padding-bottom:2px;
margin-bottom:2px;
color:chocolate;
text-transform:uppercase;
font-size: inherit;
font-size: 1.5em;
}
h2 {
font-family:Verdana, Geneva, sans-serif;
padding-bottom:0px;
margin-bottom:0px;
color:chocolate;
text-transform:uppercase;
font-size: 1.3em;
}
h3 {
font-family:Verdana, Geneva, sans-serif;
padding-bottom:2px;
margin-bottom:2px;
}
table.sales td {
padding: 4px 10px 4px 10px;
}
table.sales th {
padding: 5px 10px 5px 10px;
background-color:#CCC;
}
tr.saleline td {
border-bottom-color:chocolate;
border-bottom-width: 1pt;
border-bottom-style: solid;
vertical-align: top;
}
.signature {
display: none;
}
.horizontal-line {
border: 0;
height: 4pt;
color:chocolate;
background-color: chocolate;
}
.total {
font-weight:bold;
font-size:1.1em;
background-color:#CCC;
}
.block1 {
text-align:left;
vertical-align:bottom
}
.block2 {
text-align:right;
vertical-align:bottom
}
.block3 {
text-align:left;
vertical-align:top;
}
.block4 {
text-align:left;
vertical-align:top;
}
.block5 {
text-align:right;
vertical-align:bottom;
}
.block6 {
text-align:left;
vertical-align:top;
margin-top: 15px;
}
.block7 {
text-align:left;
vertical-align:top;
margin-top: 15px;
}
.block8 {
text-align:left;
vertical-align:bottom;
}
.block9 {
text-align:center;
vertical-align:bottom;
}
.block10 {
text-align:right;
vertical-align:bottom;
}
.block11 {
text-align:left;
padding: 25px 0 15px 0;
}
.extracols {
border-style:solid;
border-color:gray;
}
table.extracols {
border-top-width: 1pt;
border-right-width: 0;
border-bottom-width: 1pt;
border-left-width: 1pt;
border-collapse:collapse;
margin: 0 0 15pt 0;
}
table.extracols th {
padding: 5px 10px 5px 10px;
border-top-width: 0;
border-right-width: 1pt;
border-bottom-width: 0;
border-left-width: 0;
border-color:gray;
border-style:solid;
background-color:#CCC;
}
table.extracols td {
padding: 4px 10px 4px 10px;
border-top-width: 0;
border-right-width: 1pt;
border-bottom-width: 0;
border-left-width: 0;
border-color:gray;
border-style:solid;
background-color:#FFF;
}
#footer {
margin-top: 35px;
}
.footer-text {
font-size: inherit;
font-size: 0.97em
}
</style>
</head>
<body style="padding: 20 20 20 20">
<table width="100%">
<tr>
<td style="padding-bottom:20px"><table width="100%">
<tr>
<td style="text-align:left;"></td>
<td class="block2" align="right"><h3>Y.P.Brothers</h3>
No:55/B,<br/>Samagipura,<br/>Sewanagala.
<br/>077-6977139
<br/>mecduino#gmail.com
<br/>
</td>
</tr>
</table></td>
</tr>
<tr>
<td><hr class="horizontal-line"/></td>
</tr>
<tr>
<td><table width="100%">
<tr>
<td style="padding:10px 0 20px 0;"><table width="100%">
<tr>
<td width="33%" class="block3"><strong>Bill To</strong><br />
ANUSHA SURIYA<br/>
</td>
<td class="block4"><strong></strong><br />
</td>
<td class="block5" align="right"><h1>invoice #1</h1>
<b>Date</b>: Oct 9, 2015
<br/><b>Due Date</b>: Oct 9, 2015
</td>
</tr>
</table></td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td><table width="100%" class="sales">
<!-- Headers -->
<tr>
<th align="center">Qty</th> <th align="center">Item</th> <th align="right">Price</th> <th align="right">Amount</th>
</tr>
<!-- Rows -->
<tr class="saleline"> <td align="left">12</td> <td align="left">helaligth 35/=</td> <td align="right">35.00</td> <td align="right">420.00</td> </tr>
<tr class="saleline"> <td align="left">12</td> <td align="left">200p CR SR 195/=</td> <td align="right">195.00</td> <td align="right">2,340.00</td> </tr>
<tr class="saleline"> <td align="left">36</td> <td align="left">Sunlight 35g</td> <td align="right">6.00</td> <td align="right">216.00</td> </tr>
<!-- Totals -->
<tr><td align="right" colspan="3">Subtotal</td><td align="right">2,976.00</td></tr><tr><td align="right" colspan="3"><b>TOTAL</b></td><td align="right"><b>2,976.00</b></td></tr><tr><td align="right" colspan="3">Less Payment</td><td align="right">2,760.00</td></tr><tr class="total"><td align="right" colspan="3"><strong>Balance Due</strong></td><td align="right">216.00</td></tr>
</table></td>
</tr>
</table></td>
</tr>
<tr>
<td><table width="100%" style="margin-top:30px">
<tr>
<td width="50%" class="block6"><h2></h2>
</td>
<td width="50%" class="block7" align="right"><h2></h2>
</td>
</tr>
</table></td>
</tr>
<tr>
<td><table class="block11" width="100%">
<tr>
<td><table></table></td>
</tr>
</table></td>
</tr>
<tr>
<td></td>
</tr>
</table>
<div class="signature">
<table border="0" cellspacing="2" cellpadding="2" align="left">
<tr>
<td style="padding-bottom:30px"></td>
</tr>
<tr>
<td><b>Signed by:</b>
<br/><b>Date:</b>
<br/><b>Signature:</b><br/></td>
</tr>
</table>
</div>
<div id="footer">
<table width="100%" border="0" cellpadding="2">
<tr>
<td align="center"><span class="footer-text">Thank you for your business.</span></td>
</tr>
</table>
</div>
</body>
</html>
You need an html parser, try this one http://htmlagilitypack.codeplex.com/
Load page into HtmlDocument
HtmlWeb htmlWeb = new HtmlWeb();
HtmlDocument htmlDocument = htmlWeb.Load("url");
Get table with specified Id
HtmlNode table = htmlDocument.DocumentNode.Descendants("table").SingleOrDefault(x => x.Id == "tableId");
Loop through nodes to find values
foreach(HtmlNode child in table.ChildNodes)
{
if (child.NodeType != HtmlNodeType.Text)
{
Console.WriteLine(child.Name);
}
}
More you can check here http://www.codeproject.com/Articles/691119/Html-Agility-Pack-Massive-information-extraction-f
You have to use parseHTML function of jquery and then loop through each element to get the values. Below is the working example (It can be more refined as per your need)
$(document).ready(function () {
var str = '<tr><td align="right" colspan="3">Subtotal</td><td align="right">2,976.00</td></tr><tr><td align="right" colspan="3"><b>TOTAL</b></td><td align="right"><b>2,976.00</b></td></tr><tr><td align="right" colspan="3">Less Payment</td><td align="right">2,760.00</td></tr><tr class="total"><td align="right" colspan="3"><strong>Balance Due</strong></td><td align="right">216.00</td></tr>';
var html = $.parseHTML(str);
$.each(html, function (index, element) {
if ($(this).find("td:first").html() == "Subtotal")
console.log($(this).find("td:last").html());
else if ($(this).find("td:first b").html() == "TOTAL")
console.log($(this).find("td:last b").html());
else if ($(this).find("td:first").html() == "Less Payment")
console.log($(this).find("td:last").html());
else if ($(this).find("td:first strong").html() == "Balance Due")
console.log($(this).find("td:last").html());
});
});

Parse HTML with HTML Agility Pack

I need to parse HTML file with HTML Agility Pack. Here is div with class attribute = divTableBodyText and table inside it. I need to get table's content. I created class for data but don't know how get data.
<html>
<body>
<div class="divTableBodyText">
<table class="tableBodyText fdff_L" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<span class="fontSize textBold">Выберите тариф.</span> Разница цен в пределах одного
типа тарифа может возникнуть из-за условий выполнения рейса, связанных с колличеством
пересадок и доступностью мест. Цены указаны для взрослого пассажира с учетом Сборов
/ Налогов.
</td>
</tr>
<tr>
<td>
</td>
</tr>
</tbody>
</table>
<div class="FFInfoPanel">
</div>
<table class="fdff_tableFF" cellspacing="0">
<tbody>
<tr>
<th>
</th>
<th>
Тип тарифа
</th>
<th width="55%">
Описание тарифа
</th>
<th>
Минимальная цена
</th>
<th>
Другие авиарейсы
</th>
</tr>
<tr class="">
<td style="background-color: rgb(255, 255, 255); border-right: medium none; padding: 0px 4px 0px 0px;">
</td>
<td class="textBold" width="15%">
Special-Kazakhstan
</td>
<td class="wrap" id="FN_0" width="55%">
Специальный тариф экономического класса с ограничениями <a href="javascript:fareFamilyDescriptionPopUp.redirectToAnExternalPopUp('http://www.airastana.com/int/ru/Fare-Family-Special-Kazakhstan.aspx');">
Дополнительная информация</a>
</td>
<td style="background-color: rgb(255, 255, 255); color: rgb(0, 0, 0);" class="white"
id="FRB_1_0" _isdisabled="false" width="15%">
<input id="RB0" name="FamilyButton" value="0|1" onclick="javascript:FDFF.selectRecommendationSet('0', true,'0', 'FRB_1_0',false);"
checked="checked" type="radio">
47 917 KZT
</td>
<td class="white" id="FRB_2_0" _isdisabled="" width="15%">
</td>
</tr>
<tr class="bgrd">
<td style="background-color: rgb(255, 255, 255); border-right: medium none; padding: 0px 4px 0px 0px;">
</td>
<td class="textBold" width="15%">
Flexible-Kazakhstan
</td>
<td class="wrap" id="FN_1" width="55%">
Специальный тариф экономического класса с возможностью бесплатного перебронирования
до отправления. <a href="javascript:fareFamilyDescriptionPopUp.redirectToAnExternalPopUp('http://www.airastana.com/int/ru/Fare-Family-Flexible-Kazakhstan.aspx');">
Дополнительная информация</a>
</td>
<td class="white" id="FRB_1_1" _isdisabled="false" width="15%">
<input id="RB1" name="FamilyButton" value="1|1" onclick="javascript:FDFF.selectRecommendationSet('1', true,'1', 'FRB_1_1',false);"
type="radio">
52 397 KZT
</td>
<td class="white" id="FRB_2_1" _isdisabled="" width="15%">
</td>
</tr>
<tr class="">
<td style="background-color: rgb(255, 255, 255); border-right: medium none; padding: 0px 4px 0px 0px;">
</td>
<td class="textBold" width="15%">
Full flexible
</td>
<td class="wrap" id="FN_2" width="55%">
Нормальный тариф экономического класса без ограничений <a href="javascript:fareFamilyDescriptionPopUp.redirectToAnExternalPopUp('http://www.airastana.com/int/ru/Fare-Family-Full-Flexible.aspx');">
Дополнительная информация</a>
</td>
<td class="white" id="FRB_1_2" _isdisabled="false" width="15%">
<input id="RB2" name="FamilyButton" value="2|1" onclick="javascript:FDFF.selectRecommendationSet('2', true,'2', 'FRB_1_2',false);"
type="radio">
56 267 KZT
</td>
<td class="white" id="FRB_2_2" _isdisabled="" width="15%">
</td>
</tr>
<tr class="bgrd">
<td style="background-color: rgb(255, 255, 255); border-right: medium none; padding: 0px 4px 0px 0px;">
</td>
<td class="textBold" width="15%">
Business-Kazakhstan
</td>
<td class="wrap" id="FN_3" width="55%">
Нормальный тариф бизнес класса с некоторыми ограничениями <a href="javascript:fareFamilyDescriptionPopUp.redirectToAnExternalPopUp('http://www.airastana.com/int/ru/Fare-Family-Business-Kazakhstan.aspx');">
Дополнительная информация</a>
</td>
<td class="white" id="FRB_1_3" _isdisabled="false" width="15%">
<input id="RB3" name="FamilyButton" value="3|1" onclick="javascript:FDFF.selectRecommendationSet('3', true,'3', 'FRB_1_3',false);"
type="radio">
89 557 KZT
</td>
<td class="white" id="FRB_2_3" _isdisabled="false" width="15%">
<input name="FamilyButton" value="4|2" onclick="javascript:FDFF.selectRecommendationSet('4', true,'3', 'FRB_2_3',false);"
type="radio">
93 951 KZT
</td>
</tr>
<tr class="">
<td style="background-color: rgb(255, 255, 255); border-right: medium none; padding: 0px 4px 0px 0px;">
</td>
<td class="textBold" width="15%">
Business
</td>
<td class="wrap" id="FN_4" width="55%">
Нормальный тариф бизнес класса без ограничений. Почувствуйте настоящий комфорт!
<a href="javascript:fareFamilyDescriptionPopUp.redirectToAnExternalPopUp('http://www.airastana.com/int/ru/Fare-Family-Business.aspx');">
Дополнительная информация</a>
</td>
<td class="white" id="FRB_1_4" _isdisabled="false" width="15%">
<input id="RB4" name="FamilyButton" value="5|1" onclick="javascript:FDFF.selectRecommendationSet('5', true,'4', 'FRB_1_4',false);"
type="radio">
98 345 KZT
</td>
<td class="white" id="FRB_2_4" _isdisabled="" width="15%">
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
you can try somethink like this maybe it would help
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(//your html document);
foreach (HtmlNode div in doc.DocumentNode.SelectNodes("//div[#class='divTableBodyText']")){
foreach (HtmlNode table in div.DocumentNode.SelectNodes("table")) {
foreach (HtmlNode tbody in div.DocumentNode.SelectNodes("tbody")) {
foreach (HtmlNode row in tbody.SelectNodes("tr")) {
foreach (HtmlNode cell in row.SelectNodes("td")) {
Console.WriteLine(cell.InnerText);
}
}
}
}
}

Categories