Vision
From String to DataSet and back again
January 2006
Introduction
There are cases when all you want is a dataset, and all you've got is a string. There are also cases when you want a string, but all you have is a dataset. For example, if you call a method of a queued component in Enterprise Services the parameters should support the IPersist interface. This means passing a dataset as an argument is out of the question. Instead you could convert a dataset to a string in the client, and convert it back to a dataset in the queued component. This turns out to be a little bit tricky if you don't want to save data to the file system, so this article shows how to do this.
Convert or Converter
In .NET the System.Convert handles conversions from one datatype to another. The Convert class can't help in this case, so we'll create our own conversion class. Looking at it's name we noticed the name of the Convert class conflicts with the Class name rule, which states a name should be a noun (possibly qualified by nouns or adjectives) or an adjective (also possibly qualified by nouns or adjectives). Adjectives should only be used for deferred classes which describe some kind of structural property. The name of such classes tend to end in -able. For example: a Cloneable class describes the structural property that some classes can be copied by value. So instead, we'll call our class Converter, not Convert.
From DataSet to String
The easiest way to do this is to call dsData.GetXml();, dsData being a dataset. However, if you want to have more control over the conversion, for example, if you want to change the encoding type, you could also create a custom conversion method. The following code converts a dataset to a string. To use it, import the following namespaces:
- System.Text;
- System.IO;
- System.Data;
- System.Xml;
{
MemoryStream objStream = new MemoryStream();
dsData.WriteXml(objStream);
XmlTextWriter objXmlWriter = new XmlTextWriter(objStream, Encoding.UTF8);
objStream = (MemoryStream) objXmlWriter.BaseStream;
UTF8Encoding objEncoding = new UTF8Encoding();
return objEncoding.GetString(objStream.ToArray());
}
From String to DataSet
The following code converts a string to a dataset. To use it, import the following namespaces:
- System.IO;
- System.Data;
{
StringReader objReader = new StringReader(strXmlData);
DataSet dsData = new DataSet();
dsData.ReadXml(objReader);
return dsData;
}
The client
It's easy to use these conversion methods. Check out the following client code:
string strData = "<data>test</data>";DataSet dsData = Converter.ToDataSet(strData);
string strData2 = Converter.ToString(dsData);
Comments?
By the way, if anybody knows of other ways to do these these conversions, we'd love to hear it! Drop us a line at info@lcbridge.nl.