Wednesday, October 20, 2010

Save DataSet as XML and then Recreate the DataSet from saved XML

In this example, the DataSet is also prepended with a distinct node that can be used to include specific data the DataSet didn't include.

using(DataSet ds = GetSpecificData(dataID)){
  XmlDocument xd = new XmlDocument();
  //Here is where the unique node is created and added to the XmlDocument
  XmlNode node = xd.CreateNode(XmlNodeType.Element, "NewRootOfXML", null);
  xd.AppendChild(node);

  using(MemoryStream ms = new MemoryStream()) {
    ds.WriteXml(ms);

    //Reset the position to the start of the stream
    ms.Seek(0, SeekOrigin.Begin);

    StreamReader sr = new StreamReader(ms);
    node.InnerXml = sr.ReadToEnd();
  }

  xd.SaveTheXML();
}

  XmlDocument xDoc = TheSavedXML();
  XmlNode nd = xDoc .SelectSingleNode("/NewRootOfXML");

  DataSet data = new DataSet();
  XmlTextReader reader = new XmlTextReader(nd.InnerXml, XmlNodeType.Element, null);
  data.ReadXml(reader);

No comments: