Home > database >  Add columns do DataTable with loop from html file
Add columns do DataTable with loop from html file

Time:08-17

I want to add columns to my DataTable with the help of foreach from my <th> tags.
I have some problem with it. I don't understand why there is an null exception. In my HTML file i don't have any empty tags.
Fragment of my C# code:

DataTable dt = new DataTable();
int i = 0;
HtmlNode table = doc.DocumentNode.SelectSingleNode("//table[1]");
foreach (var row in table.SelectNodes("tr"))
{
    var headers = row.SelectNodes("th");
    foreach (var el in headers)
    {
        if (headers != null)
        {
           dt.Columns.Add(headers[i].InnerText);
           i  ;
        }
    }
}

There is a fragment of my HTML file:

<table>
<colgroup><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/></colgroup>
<tr><th>id</th><th>inserted_at</th><th>DisplayName</th><th>DistinguishedName</th><th>Enabled</th><th>GivenName</th><th>HomeDirectory</th><th>Manager</th><th>Name</th><th>ObjectClass</th><th>ObjectGUID</th><th>SamAccountName</th><th>Surname</th><th>UserPrincipalName</th><th>RowError</th><th>RowState</th><th>Table</th><th>ItemArray</th><th>HasErrors</th></tr>

CodePudding user response:

This works for your html:

var str = @"<table>
<colgroup><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/><col/></colgroup>
<tr><th>id</th><th>inserted_at</th><th>DisplayName</th><th>DistinguishedName</th><th>Enabled</th><th>GivenName</th><th>HomeDirectory</th><th>Manager</th><th>Name</th><th>ObjectClass</th><th>ObjectGUID</th><th>SamAccountName</th><th>Surname</th><th>UserPrincipalName</th><th>RowError</th><th>RowState</th><th>Table</th><th>ItemArray</th><th>HasErrors</th></tr>";

var hdoc = new HtmlAgilityPack.HtmlDocument();

hdoc.LoadHtml(str);

var headerElements = hdoc.DocumentNode.Descendants("th");

foreach(var headerElement in headerElements)
{
    Console.WriteLine(headerElement.InnerText);
}

CodePudding user response:

I also need to select it from specific table so..
This actually worked for me:

HtmlNode table = doc.DocumentNode.SelectSingleNode("//table[1]");
var headerElements = table.Descendants("th");
foreach (var headerElement in headerElements)
{
    dt.Columns.Add(headerElement.InnerText, typeof(string));
}
  • Related