Follow by Email

Monday, 25 August 2014

Convert HTML content values to Object in C# using Html Agility Pack (HAP)

In below code sample we are passing HTML in variable of name dataStream, In HTML we have a table of which we made to convert <th> and <td> in objects directly, using HAP(Html Agility Pack) need to be added using Nuget Package in our Native Application.
Sample Code:
using HtmlAgilityPack;
// Import Html table to datatable, Using “Html Agility Pack(Nuget)”
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(dataStream);
var headers = doc.DocumentNode.SelectNodes(“//tr/th”);
List<string> headingList = new List<string>();
List<string> valueList = new List<string>();
// Add th values in h
foreach (HtmlNode header in headers)
{
var headText = header.InnerText; //Get head columns from th
headText = headText.Replace(“:”, “”); // Remove colon(:) sign from head text
headingList.Add(headText);
}
// Select rows with td elements
foreach (var row in doc.DocumentNode.SelectNodes(“//tr[td]“))
{
var valueText = row.SelectNodes(“td”).Select(td => td.InnerText).ToArray();
var strValue = valueText[0].ToString();
valueList.Add(strValue);
}
Reference Link:

0 comments:

Post a Comment


                                                            

 
Design by Abhinav Ranjan Sinha