Wednesday, July 30, 2008

XML Serialization in .Net Framework (Write Xml from Dataset)

WHAT IS SERIALIZATION ?
Serialization is converting an object to a format in which it can be saved (exported) as file or a physical medium. A simple and basic example would be, if we create an XML from a Dataset it is called Serialization.

CODE:
try
{
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlConnection myConnection;
String connStr = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ToString();

SqlConnection myConnection = new SqlConnection(connStr);
String sql = "select * from tblCategory";
da = new SqlDataAdapter(sql, myConnection);
ds.Clear();
da.Fill(ds, "tblCategory");
ds.WriteXml(Server.MapPath("~/xmls/info.xml"));
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

The above code will write an XML file called info.xml from a Dataset called "ds" into xmls folder in root of website.


Options
Alternatively we can use some advanced options to format the data which is being written.

ds.WriteXml(Server.MapPath("~/xmls/info.xml", XmlWriteMode.WriteSchema);

Some options are. Some of the attributes available in Microsoft .Net Framework are as follows:

XmlWriteMode.DiffGram — Writes the entire DataSet as a DiffGram.
XmlWriteMode.IgnoreSchema — Writes the current contents of the DataSet as XML data, without an XML Schema Definition language (XSD) schema.
XmlWriteMode.WriteSchema — Writes the current contents of the DataSet as XML data with the relational structure as inline XSD schema.