Saturday, August 09, 2003


Source: Steve Eichert

One of the advantages of using DataSets is their support for Xml. By using the ReadXml() and WriteXml() methods on the DataSet developers can quickly retrieve an Xml representation of a DataSet, as well as re-hydrate a DataSet with data from an Xml file.

By default our custom written business objects don't have support for such features. The Xml Serialization features in the .NET Framework allow us to add Xml support to our objects with very minimal effort. The code below shows an example implementation of a ToXml() method for returning an Xml representation of a business object, and a FromXml() method that returns an entity object re-hydrated with values from an Xml string.

/// <summary>
///
Retrieve a Xml representation of the business object.
///
</summary>
/// <returns>String of xml representing the object.
</returns>
public virtual string ToXml()
{

string xml;
System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(this.GetType());
serializer.Serialize(stream, this);
 xml = System.Text.Encoding.UTF8.GetString(stream.ToArray());
stream.Close();
return xml;

}

/// <summary>
///
Re-hydrate an entity object from an Xml string.
///
</summary>
/// <param name=XML>The xml representation of the object
</param>
/// <returns>The re-hydrated IEntityObject
</returns>
public IEntityObject FromXml(string xml)
{

IEntityObject entity = null;
System.IO.StringReader reader = null;
try
{

System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(this.GetType());
reader = new System.IO.StringReader(xml);
entity = (IEntityObject)serializer.Deserialize(reader);

}
finally
{

if(reader!=null) reader.Close();

}

return entity;

}

[Steve Eichert]
1:28:37 PM    trackback []     Articulate []