65.9K
CodeProject is changing. Read more.
Home

Convert XML Data to DataSet and Back

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.57/5 (16 votes)

May 18, 2005

CPOL
viewsIcon

143249

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