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

Code To Convert rupees(numbers) into words using C#.Net

Introduction: In my previous article I have explained about how to validate emailid using javascript . In this article I am going to explain about code used to convert rupees(numbers) into words using C#.Net . Explanation: For explanation purpose I have a page. It has a textbox to input the numbers. And when you click on the convert to words button then it will convert the input numbers into words and shows it in the below label. Below is the C# code used to do this functionality. public static string NumbersToWords( int inputNumber) {     int inputNo = inputNumber;     if (inputNo == 0)         return "Zero" ;     int [] numbers = new int [4];     int first = 0;     int u, h, t;     System.Text. StringBuilder sb = new System.Text. StringBuilder ();     if (inputNo < 0)     { ...

Dynamically programmatically add contols at run time Asp.Net

Introduction: In my previous article I have explained about What is View State? How to Store and retrieve values from View State . In this article I am going to explain how to add controls programmatically on run time. Explanation: This example adds a text box and button to a Web Forms page at run time. It also dynamically binds an event handler to the button's   Click   event. The handler displays the values of the dynamically generated text box. The controls are added into a   Panel   Web server control, which acts as a placeholder. The controls are separated in the panel with line breaks (HTML <BR> elements), which are added to the panel using the   LiteralControl   control.

C# Extension Methods Example

In this article i am going to explain about Extension Methods  with example. Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. If you do implement extension methods for a given type, remember the following points: An extension method will never be called if it has the same signature as a method defined in the type. Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions, they will all be brought into scope by the using Extensions; directive. ...