Convert XML Data to DataSet and Back






2.57/5 (16 votes)
This article describes the functions to convert the XML data to an untyped dataset and get the XML back from untyped dataset
Using the Code
Use this function to save an XML string
to DataSet
:
// Function to convert passed XML data to dataset
public DataSet ConvertXMLToDataSet(string xmlData)
{
StringReader stream = null;
XmlTextReader reader = null;
try
{
DataSet xmlDS = new DataSet() ;
stream = new StringReader(xmlData);
// Load the XmlTextReader from the stream
reader = new XmlTextReader(stream);
xmlDS.ReadXml(reader);
return xmlDS;
}
catch
{
return null;
}
finally
{
if(reader != null) reader.Close();
}
}// Use this function to get XML string from a dataset
// Function to convert passed dataset to XML data
public string ConvertDataSetToXML(DataSet xmlDS)
{
MemoryStream stream = null;
XmlTextWriter writer = null;
try
{
stream = new MemoryStream();
// Load the XmlTextReader from the stream
writer = new XmlTextWriter(stream, Encoding.Unicode);
// Write to the file with the WriteXml method.
xmlDS.WriteXml(writer);
int count = (int) stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
UnicodeEncoding utf = new UnicodeEncoding();
return utf.GetString(arr).Trim();
}
catch
{
return String.Empty ;
}
finally
{
if(writer != null) writer.Close();
}
}
History
- 18th May, 2005: Initial post