Wednesday, November 03, 2004

Converting a XML string to dataset (.net, webservice)

Web services, great stuff eh?a webservice IMHO should pass data back to the consumer. In one of the microsoft meeting for partners that was held recently, it was said that webservices should not pass dataset back, instead, they should pass back XML. Resons being, 1. Datasets are not universal, but XML is(so you dont have to change the webservice if you consumer changes to JAVA or SAP) 2. Dataset has a lot more overhead due to the included schemas, hence using XML reduces the data sent across size drastically)
Assuming an existing webservice was sending a dataset back to the consumer and the consumer was using this dataset. Now, i want to change this webservice method to pass xml. so this is wat I doon the webservice method :
=================
instead of returning dataset ( retrurn myDataset; )
I return xml string ( return myDataset.GetXml(); )
Note : Calling GetXml is identical to calling WriteXml(); with XmlWriteMode set to IgnoreSchema.Since GetXml(); already passes the content of a data set without the dataset's schema, we dont have to worry about removing the schema explicitly.on the Consumer side :
===============
instead of getting dataset and using it
( something.DataSource = myReturnedDatasetFromWebService)
we need to convert the xml string that we are getting and cast is to a dataset as below
' dataset to hold the data
Dim ds As New DataSet
'TextReader to get the XML
Dim xmlrder As System.Xml.XmlTextReader
'Point the xmltextreader to the string with xml contents and make it to expect an XML document
xmlrder = New System.Xml.XmlTextReader(strXML, System.Xml.XmlNodeType.Document, Nothing)
' Read all of the XML as one chunk
xmlrder.ReadOuterXml()
' Read the outer XML into the Dataset
ds.ReadXml(xmlrder)
' Tell the datagrid to use this dataset
something.DataSource = ds
' Bind the data
something.DataBind()
So, there you go... now you are just passing data(in form of a string) from the webservice.
This post is based upon the code from "Ken Cox"