Create a WebService in ASP.Net that return an XML Document.

Posted by Nordes on September 14th, 2008 filed in C#

I know that you can find a lot of tutorial over the internet to create a simple Web Services that return data. Personally, I just wanted to create a quick tutorial to return an XML Document from a DataSet.

First of all, you will need Visual Studio 2005 or 2008. Once you’ve created a web site project or an web site application project, you need to add to the solution a “Web Service” page. You can call that web service “Test.asmx”. By default you will see an “Hello World” test function. To try out that fabulous function press “F5″ to compile and run from the test.asmx page. By doing that, it will display you the available function for your Web Services. Click on it to see how to call that function by soap or HTTP post. You also have in that screen a button to invoke your web method inside your service. If you had any primitive parameters (Ex.: string, int, bool, …), you would see the inputs to call your method. In your case, only click on the button “Invoke”. The result displayed on your browser should be an “Hello World” text.

Let’s get back to the “Test.asmx” and replace the hello world function by “GetXMLDataSetData”. Don’t put any arguments at the moment. Inside that function, put the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[WebMethod]
public XmlDocument GetXMLDataSetData() {
	XmlDocument myXmlDocument = new XmlDocument();
	DataSet myDataSet = new DataSet("MyDataSetName");
	DataTable myDataTable = new DataTable("MyDataTableStuff");
 
	myDataSet.Tables.Add(myDataTable);
 
	myDataTable.Columns.Add("FirstName", typeof(string));
	myDataTable.Columns.Add("LastName", typeof(string));
	myDataTable.Columns.Add("FullName", typeof(string), "LastName + ', ' + FirstName");
	DataRow dtrow = myDataTable.NewRow();
	dtrow["FirstName"] = "Nordes";
	dtrow["LastName"] = "Lamarre";
 
	myDataTable.Rows.Add(dtrow);
	myDataTable.AcceptChanges();
 
	myXmlDocument.LoadXml(myDataSet.GetXml());
    return myXmlDocument;
}

The result given by clicking the invoke button will be the following:

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
<MyDataSetName>
  <MyDataTableStuff>
    <FirstName>Nordes</FirstName>
    <LastName>Lamarre</LastName>
    <FullName>Lamarre, Nordes</FullName>
  </MyDataTableStuff>
</MyDataSetName>

What you could also do is calling a stored procedure that is returning you a dataset. From that DataSet, you only return the tables you need with the appropriate data.


One Response to “Create a WebService in ASP.Net that return an XML Document.”

  1. buy levitra without prescription Says:

    pile cares bigregister googles matched facet wakefield resilient buzzmetrics bubba vksj epistemology

Leave a Comment