Skip to main content

ASP.Net - Convert XML to Datatable in C#.net, VB.Net


I have the below XML File 

<?xml version="1.0" encoding="utf-8"?>
<root>
  <Employee>
    <Id>1</Id>
    <EmpName>Kannadasan</EmpName>
    <Gender>Male</Gender>
    <Dept>Reading Books</Dept>
  </Employee>
  <Employee>
    <Id>2</Id>
    <EmpName>Kaviyarasan</EmpName>
    <Gender>Male</Gender>
    <Dept>Playing Games</Dept>
  </Employee>
  <Employee>
    <Id>3</Id>
    <EmpName>Ramkumar</EmpName>
    <Gender>Male</Gender>
    <Dept>Reading Books</Dept>
  </Employee>
  <Employee>
    <Id>4</Id>
    <EmpName>Xavier Selvaraj</EmpName>
    <Gender>Male</Gender>
    <Dept>Playing Games</Dept>
  </Employee>
</root>


ASP.Net Code:

<!DOCTYPE html>
<html>
<head runat="server">
    <title>Convert XML to Data Table</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="grdTable" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

C#.Net Code

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq;
using System.Xml.Linq;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        XElement xele = XElement.Load(Server.MapPath("test.xml"));//get your file
        // declare a new DataTable and pass your XElement to it
        DataTable dt = XElementToDataTable(xele);
        grdTable.DataSource=dt;
        grdTable.DataBind();
    }
    public DataTable XElementToDataTable(XElement x)
    {
        DataTable dtable = new DataTable();

        XElement setup = (from p in x.Descendants() select p).First();
        // build your DataTable
        foreach (XElement xe in setup.Descendants())
            dtable.Columns.Add(new DataColumn(xe.Name.ToString(), typeof(string))); // add columns to your dt

        var all = from p in x.Descendants(setup.Name.ToString()) select p;
        foreach (XElement xe in all)
        {
            DataRow dr = dtable.NewRow();
            foreach (XElement xe2 in xe.Descendants())
                dr[xe2.Name.ToString()] = xe2.Value; //add in the values
            dtable.Rows.Add(dr);
        }
        return dtable;
    }
}



Below is the equivalent VB.Net

Imports System.Collections.Generic
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Linq
Imports System.Xml.Linq
Imports System.Data

Partial Public Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        Dim x As XElement = XElement.Load(Server.MapPath("test.xml"))
        'get your file
        ' declare a new DataTable and pass your XElement to it
        Dim dt As DataTable = XElementToDataTable(x)
        grdTable.DataSource = dt
        grdTable.DataBind()
    End Sub
    Public Function XElementToDataTable(x As XElement) As DataTable
        Dim dt As New DataTable()

                        Dim setup As XElement = (From p In x.Descendants()p).First()
        For Each xe As XElement In setup.Descendants()
            ' build your DataTable
            dt.Columns.Add(New DataColumn(xe.Name.ToString(), GetType(String)))
        Next
        ' add columns to your dt
                        Dim all = From p In x.Descendants(setup.Name.ToString())p
        For Each xe As XElement In all
            Dim dr As DataRow = dt.NewRow()
            For Each xe2 As XElement In xe.Descendants()
                dr(xe2.Name.ToString()) = xe2.Value
            Next
            'add in the values
            dt.Rows.Add(dr)
        Next
        Return dt
    End Function
End Class


The Output Will be:

IdEmpNameGenderDept
1KannadasanMaleReading Books
2KaviyarasanMalePlaying Games
3RamkumarMaleReading Books
4Xavier SelvarajMalePlaying Games


You may also like

  1. C# Extension Methods Example
  2. How to generate random no in C#.Net
  3. ASP.Net Tutorials For Beginners
  4. Add httpcookie using c#.net
  5. Add query string value to hyperlink in C#.net/Asp.Net
  6. C# code to bind XML data to Grid view
  7. C# code to convert string to byte array and byte array to string in ASP.Net - New !!
  8. C# code to send mail using smtp from gmail,yahoo mail and live mail
  9. Check textbox is changed or not using javascript C#.net
  10. Check uncheck all checkboxes in grid view using jquery

Comments

Popular posts from this blog

Sort Dictionary Based On Value In Asp.Net And C#.Net | Convert Dictionary into KeyValuePair or KeyValuePair into Dictionary.

In this tutorial i am going to explain about how to sort dictionary object based on value in asp.net and C#.Net or convert unsorted dictionary to sorted dictionary object in C#.Net and VB.Net or Convert Dictionary into KeyValuePair or KeyValuePair into Dictionary.

Code to create log files in C#.Net|Asp.Net

Introduction: In my previous article I have explained about how to create, delete and check whether the directory exists using C#.Net . In this article I am going to explain about  How to create log files in C#.Net. Explanation: Log files are useful to track any runtime errors and exceptions in all the applications. Below code will code will get the Message and Pagename as the input and creates the log file in that date. For that first i have imported below two namespaces.

Geckofx Browser in Winform Application

Bored with IE browser in your winform application ? Want to do everything as you doing in your Firefox or Chrome Browser ? Play with automation ? Then here is your choice . Introduction:  GeckoFX is a Windows Forms control written in clean, commented C# that embeds the Mozilla Gecko browser control in any Windows Forms Application. It also contains a simple class model providing access to the HTML and CSS DOM . GeckoFX was originally created by Andrew Young for the fast-growing visual CSS editor, Stylizer . It is now released as open-source under the Mozilla Public License.  You can download it here :   Geckofx 22.0 And the supporting file Xulrunner here :   Xulrunner Files Hope you have downloaded above two files. Here our journey going to start. Create your winform application in visual studio and do the following: right click the toolbox -> Choose items -> Browse the "Geckofx-winforms.dll" and click "yes" for “Load it anyw...