Thursday, 27 November 2008

Convert XML to a DataSet and visa versa in C#

Simple... but for my own reference:

/// 
/// Convert the xml string into a DataSet object
/// 
/// The xml string to convert
/// The DataSet instance
public DataSet ConvertXmlToDataSet(string xml)
{
using (StringReader reader = new StringReader(xml))
{
using (XmlTextReader xmlReader = new XmlTextReader(reader))
{
DataSet dataSet = new DataSet();
dataSet.ReadXml(xmlReader);
return dataSet;
}
}
}

/// 
/// Converts a DataSet into an xml string representation
/// 
/// The DataSet to convert
/// The xml string representation of the DataSet
public string ConvertDataSetToXml(DataSet dataSet)
{
using (StringWriter writer = new StringWriter())
{
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(writer))
{
dataSet.WriteXml(xmlTextWriter);
return writer.ToString();
}
}
}

No comments: