How to create XML file from Dataset

XML, as a tag-based language, operates on the principle that a document consists of various XML tags encapsulating specific information. To create an XML file, developers have multiple approaches at their disposal, offering flexibility and adaptability based on specific requirements and preferences.

XML file from Dataset

In the previous section, we successfully generated an XML file utilizing the XmlTextWriter Class. In this scenario, we are creating another XML file named Product.XML using an ADO.NET Dataset. To accomplish this, we follow a series of steps: Firstly, we manually construct a Datatable and populate it with the data intended for Product.XML. Subsequently, we incorporate the Datatable into a Dataset. Finally, we invoke the WriteXml method of the Dataset, passing the file name Product.XML as an argument, thereby generating the desired XML file.

Full Source C#
using System; using System.Data; using System.Windows.Forms; using System.Xml; namespace WindowsApplication1 { public partial class Form1 : Form { DataTable dt; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); dt = new DataTable(); dt.Columns.Add(new DataColumn("Product_ID", Type.GetType("System.Int32"))); dt.Columns.Add(new DataColumn("Product_Name", Type.GetType("System.String"))); dt.Columns.Add(new DataColumn("product_Price", Type.GetType("System.Int32"))); fillRows(1, "product1", 1111); fillRows(2, "product2", 2222); fillRows(3, "product3", 3333); fillRows(4, "product4", 4444); ds.Tables.Add(dt); ds.Tables[0].TableName = "product"; ds.WriteXml("Product.xml"); MessageBox .Show ("Done"); } private void fillRows(int pID, string pName, int pPrice) { DataRow dr ; dr = dt.NewRow(); dr["Product_ID"] = pID; dr["Product_Name"] = pName; dr["product_Price"] = pPrice; dt.Rows.Add(dr); } } }