Skip to main content

Pass XML as Parameter from C# to sql server

Pass XML as Parameter from C# to SQL Stored Procedure in VB.NET

Introduction:

Here I will explain how to pass or send xml file as a parameter to SQL stored procedure in asp.net usingC# and VB.NET.

Description:

Now I will explain how to pass or send xml file as a parameter to SQLstored procedure in asp.net using C# and VB.NET.

In situation I got requirement like read data from xml file and send that xml file as parameter to store procedure. My XML File Name as “Sample.xml” and that would contains data like this
<?xml version="1.0" encoding="utf-8" ?>
<users>
          <user>
                   <FirstName>Suresh</FirstName>
                   <LastName>Dasari</LastName>
                   <UserName>SureshDasari</UserName>
                   <Job>Team Leader</Job>
          </user>
          <user>
                   <FirstName>Mahesh</FirstName>
                   <LastName>Dasari</LastName>
                   <UserName>MaheshDasari</UserName>
                   <Job>Software Developer</Job>
          </user>
          <user>
                   <FirstName>Madhav</FirstName>
                   <LastName>Yemineni</LastName>
                   <UserName>MadhavYemineni</UserName>
                   <Job>Business Analyst</Job>
          </user>
</users>

Now I need to send this xml file as parameter to stored procedure for that first create xml file in your application (Right Click your application and select Add New Item >> Select XML file) and give name as “Sample.xml” and write following code in your aspx page like this 

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Send xml file as a parameter to SQL stored procedure in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSend" Text="Send XML to Database" runat="server" onclick="btnSend_Click" /><br /><br />
<b>Inserted Records Details</b> :
<asp:GridView ID="gvDetails" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>
After that add following namespaces in codebehind

C# Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;

Now add following code in code behind


protected void btnSend_Click(object sender, EventArgs e)
{
XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("Sample.xml"));
DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
if (ds.Tables.Count != 0)
{
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("prc_readxmldata", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@XMLdata"SqlDbType.Xml).Value = ds.GetXml();
SqlDataAdapter da=new SqlDataAdapter(cmd);
DataSet ds1=new DataSet();
da.Fill(ds1);
gvDetails.DataSource = ds1;
gvDetails.DataBind();
con.Close();
}
}
}

VB.NET Code


Imports System.Data
Imports System.Data.SqlClient
Imports System.Xml
Partial Class Default2
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs)

End Sub
Protected Sub btnSend_Click(ByVal sender As ObjectByVal e As EventArgs)
Dim xmlreader As New XmlTextReader(Server.MapPath("Sample.xml"))
Dim ds As New DataSet()
ds.ReadXml(xmlreader)
xmlreader.Close()
If ds.Tables.Count <> 0 Then
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("prc_readxmldata", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@XMLdata", SqlDbType.Xml).Value = ds.GetXml()
Dim da As New SqlDataAdapter(cmd)
Dim ds1 As New DataSet()
da.Fill(ds1)
gvDetails.DataSource = ds1
gvDetails.DataBind()
con.Close()
End Using
End If
End Sub
End Class
In above code I mentioned stored procedure “prc_readxmldata” now we need to create that stored procedure in database like as shown below

CREATE PROCEDURE prc_readxmldata
(
@XMLdata XML
)
AS
BEGIN
SELECT
t.value('(FirstName/text())[1]','nvarchar(120)')AS FirstName ,
t.value('(LastName/text())[1]','nvarchar(120)')AS LastName,
t.value('(UserName/text())[1]','nvarchar(120)')AS UserName,
t.value('(Job/text())[1]','nvarchar(120)')AS Job
FROM
@XMLdata.nodes('/users/user')AS TempTable(t)
END

Demo








Comments

Popular posts from this blog

.NET Core API With Dapper, Repository And UnitOfWork

  Introduction In this tutorial, you will use ASP.NET Core Web API to create a web API that returns a list of brands. This article focuses on creating web API using dapper, repository pattern, and UnitOfWork pattern in .NET 8. I will guide you through the steps by step to create web API. HTTP is not just for serving up web pages. HTTP is also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications. ASP.NET Core Web API is a framework for building web APIs on top of the .NET Framework. Creating a New Project in Visual Studio Launch Visual Studio and select Create a New Project. Creating a Core Web API Start Visual Studio and choose Create a new project. In the Create a new project dialog, select ASP.NET Core Web API Click Next. Configuring You...

.Net framework interview questions

What is the .NET Framework? The .NET Framework is a set of technologies that form an integral part of the .NET Platform. It is Microsoft’s managed code programming model for building applications. The .NET Framework has two main components: Common Language Runtime (CLR): The CLR is one of the foundation in the .NET framework and provides a common set of services for applications developed on Microsoft .Net Technologies. .NET Framework class library: The .NET framework class library is a collection of reusable types and exposes features of the runtime. It contains of a set of classes that is used to access common functionality. What is CTS (Common Type System)? The common type system (CTS) defines how types are declared, used, and managed in the runtime, and is also an important part of the runtime’s support for cross-language integration. The common type system performs the following functions: ·          Establishes a framework that...

Move Selected Gridview Rows to Another Gridview in Asp.net

Introduction :  Here I will explain how to move or transfer selected checkbox gridview rows to another  grid v iew in asp.net using c#, vb.net or copy one gridview row to another gridview in asp.net using c#, vb.net. Description :  In previous posts I explained Display images in gridview from database in asp.net, Enable/Disable checkbox in gridview based on condition,  asp.net gridview examples  and  bind data to textbox control in gridview ,  Bind data to dropdownlist  in gridview  and many articles relating to  asp.net,  c#, vb.net, c#,vb.net. Now I will explain how to move selected rows from one gridview to another gridview in asp.netusing c#, vb.net. To implement this first we need to write the code in aspx page like this  < html   xmlns ="http://www.w3.org/1999/xhtml"> < head > ...