News
IBM to offer mobile security as a service IBM will start delivering mobile security-as-a-service (MaaS) through its own cloud infrastructure in India, a move that is expected to better address in-country data requirements... IBM Spectrum Computing: IBM has enlarged its portfolio of software-defined infrastructure solutions with cognitive features for workload management.  * LiFi internet technology has been introduced, the new type of wireless internet connection that gives 100 times faster than traditional WiFi -- Invented by Professor Harald Haas from the University of Edinburgh. * Sci. Rachid Yazami has developed a smart chip that charges smartphones in less than 10 minutes. BenQ has launched BlueCore projector - Consumer electronics major BenQ has launched its first BlueCore laser light source projector. For those unaware, devices with BlueCore laser technology have a high contrast output of 80000:1 with an extended lamp life and efficiency. *** 
  Dec 14 2014 8:23AM     Michael Ryan
  0 Comments    4036 Views  
Here Michael Ryan provided a short tutorial with example, how to create XML file from Database in C#/VB.
Database
Consider the structure of Table as shown below,
Table Structure
Set the table name as shown below.
Page Design
Image belows shows page design for Creating XML file.
HTML
Below is the sample HTML code,
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>        
        <h2>
            XML CREATION (EMPLOYEE DETAILS)</h2>
            <hr >
        <br >
        <div>
            <span>Enter Employee ID: </span>
            <asp:TextBox ID="txtEmpID" runat="server"></asp:TextBox>&nbsp;&nbsp;<asp:Button ID="btnCreateXML"
                runat="server" Text="Create XML" OnClick="btnCreateXML_Click" />

        </div>
        <br >
        <div><asp:Label ID="lblMessage" runat="server"></asp:Label></div>
    </div>
    </form>
</body>
</html>
Namespaces
You will need to import the following namespace.
C#

using System.Data;
using System.Xml;
using System.Data.SqlClient;

VB

Imports System.Data
Imports System.Xml
Imports System.Data.SqlClient

Creating XML from Database
Below is the sample code for creating XML from Database in C#/VB.
GetData() method will get Employee data from Database and return it as Datatable.
For CreateXML() method takes the parameter DataSet and Path to save XML file.
C#

public DataSet GetData(int EmpID)
{
            string conString = " server=Your Server Name; database=DBName; uid=***;   password=****;";
            SqlConnection conn = new SqlConnection(conString);
            DataSet ds = new DataSet();
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("SELECT * FROM Employee where ID=" + EmpID, conn);
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                da.Fill(ds);
            }
            catch (Exception ex)
            {
                //Exception Message
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
            return ds;
}

VB

Public Function GetData(ByVal EmpID As IntegerAs DataSet

            Dim conString As String =  " server=YourServerName; database=DBName; uid=***;   password=*****;" 
            Dim conn  SqlConnection =  New (conString) 
            Dim ds  DataSet =  New () 
            Try
                conn.Open()
                Dim cmd  SqlCommand =  New ("SELECT * FROM Employee where ID=" + EmpID,conn) 
                Dim da  SqlDataAdapter =  New () 
                da.SelectCommand = cmd
                da.Fill(ds)

            Catch ex As Exception
                'Exception Message

            Finally
                conn.Close()
                conn.Dispose()
            End Try

            Return ds

End Function

Code for Create XML
C#

public void CreateXml(DataSet ds, string XmlPath)
{
            try
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    string Name = string.Empty;
                    int Age = 0;
                    int Experience = 0;

                    Name = ds.Tables[0].Rows[0]["EmployeeName"].ToString();
                    Age = int.Parse(ds.Tables[0].Rows[0]["EmployeeAge"].ToString());
                    Experience = int.Parse(ds.Tables[0].Rows[0]["EmployeeExperience"].ToString());

                    string xml = XmlTemplate().ToString().Replace("EmpName", Name).Replace("EmpAge", Age.ToString());
                    XmlPath = XmlPath + "Employee_" + Name + ".xml";
                    XmlDocument xdoc = new XmlDocument();
                    xdoc.LoadXml(xml);
                    xdoc.Save(XmlPath);
                    lblMessage.Text = "XML Created Successfully.";
                }
                else
                {
                    lblMessage.Text = "InValid Employee ID.";
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message.ToString();
            }
}

VB

Public  Sub CreateXml(ByVal ds As DataSet, ByVal XmlPath As String)

            Try

                If ds.Tables(0).Rows.Count > 0 Then
                    Dim Name As String =  String.Empty 
                    Dim Age As Integer =  0 
                    Dim Experience As Integer =  0 
 
                    Name = ds.Tables(0).Rows(0)("EmployeeName").ToString()
                    Age = Integer.Parse(ds.Tables(0).Rows(0)("EmployeeAge").ToString())
                    Experience = Integer.Parse(ds.Tables(0).Rows(0)("EmployeeExperience").ToString())
 
                    Dim xml As String =  XmlTemplate().ToString().Replace("EmpName",Name).Replace("EmpAge",Age.ToString()) 
                    XmlPath = XmlPath + "Employee_" + Name + ".xml"
                    Dim xdoc  XmlDocument =  New () 
                    xdoc.LoadXml(xml)
                    xdoc.Save(XmlPath)
                    lblMessage.Text = "XML Created Successfully."
                Else 
                    lblMessage.Text = "InValid Employee ID."
                End If
            Catch ex As Exception
                lblMessage.Text = ex.Message.ToString()

            End Try

End Sub

Create XML Tags
C#

public string XmlTemplate()
{

            string Xml = "<Employee>" +
                            "<Name>EmpName</Name>" +
                            "<Age>EmpAge</Age>" +
                            "</Employee>";
            return Xml;
}

VB

Public Function XmlTemplate() As String
 
            String Xml = "<Employee>" +
                            "<Name>EmpName</Name>" +
                            "<Age>EmpAge</Age>" +
                            "</Employee>"
            Return Xml

End Function

Code for "Create XML" Button Click Event
C#

protected void btnCreateXML_Click(object sender, EventArgs e)
{
            int EmpID = int.Parse(txtEmpID.Text);
            DataSet dsEmp = GetData(EmpID);
            CreateXml(dsEmp, "D:/");
}

VB

Protected  Sub btnCreateXML_Click(ByVal sender As ObjectByVal e As EventArgs)

            Dim EmpID As Integer =  Integer.Parse(txtEmpID.Text) 
            Dim dsEmp As DataSet =  GetData(EmpID) 
            CreateXml(dsEmp, "D:/")

End Sub

Result
Finally, the Employee.xml will be stored on the filepath(D:/Employee.xml)
I hope this page will helps to create XML from Database in ASP.Net application. Thanks.
BackToTop
Comments



 
Search
Recent Posts
Create Amazon ElasticCache Using Memcached in CSharp
Oct 29 2018 12:09PM Posted By Amose
Get Google Map Lat Lng (Geo Point) By Pincode in C#
Oct 28 2018 12:09PM Posted By Pranav
Google URL Shortener in C#
Oct 20 2018 12:09PM Posted By Sanjay
Bind Gridview from CSV file in Asp.Net C#
Oct 5 2018 12:09PM Posted By Michael
Call WebService method from jQuery in every 1 minute
Sep 26 2018 12:09PM Posted By John
Gridview custom CSS in ASP.Net
Sep 14 2018 12:09PM Posted By Micheal Ryan
Read excel file and bind to Gridview in C#
Sep 10 2018 12:09PM Posted By Micheal
Tags
Follow us on Facebook
Follow us on Google +
Recent post in your Email inbox.
Enter your email address: