In this article, I'll discuss how to read data from a SQL Server database into a DataTable and then save the DataTable data into an XML file using C#.
We will discuss two methods to convert a database table to an XML file.
Method 1. Use DataTable.WriteXml
In the first method, we will use the WriteXml method of DataTable to write the XML to a file.
The following code reads a database table by executing a command. The data returned into a DataTable. DataTable.WriteXml method takes an XML file name and writes data to it.
- Xml()
- {
- try
- {
- string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
- string CmdString = "SELECT EmployeeID, LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate, Address City, Region, PostalCode, Country, HomePhone, Extension, Notes, ReportsTo, PhotoPath FROM Employees";
- SqlConnection con;
- SqlCommand cmd;
- SqlDataAdapter sda;
- DataTable dt;
- using (con = new SqlConnection(ConString))
- {
- cmd = new SqlCommand(CmdString, con);
- con.Open();
- dt = new DataTable("Employees");
- sda = new SqlDataAdapter(cmd);
- sda.Fill(dt);
- dt.WriteXml("Employees.xml");
- con.Close();
- }
- }
- catch (Exception)
- {
- throw;
- }
- }
Method 2. XmlDocument.Save Method
In the second method, wel use a SELECT statement with a FOR XML clause to select data from the database in XML format and then we use the ExecuteXmlReader method of the SqlCommand class to load XML in an XmlDocument object. The XmlDocument.Save method saves data into XML.
- private void TableToXml()
- {
- try
- {
- string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
- string CmdString = "SELECT EmployeeID, LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate, Address City, Region, PostalCode, Country, HomePhone, Extension, Notes, ReportsTo, PhotoPath " +
- "FROM Employees FOR XML RAW('Employee'), ROOT('Employees'), ELEMENTS";
- SqlConnection con;
- SqlCommand cmd;
- XmlReader reader;
- XmlDocument xmlDoc;
- using (con = new SqlConnection(ConString))
- {
- cmd = new SqlCommand(CmdString, con);
- con.Open();
- reader = cmd.ExecuteXmlReader();
- xmlDoc = new XmlDocument();
- while (reader.Read())
- {
- xmlDoc.Load(reader);
- }
- xmlDoc.Save("Employees.xml");
- }
- }
- catch (Exception)
- {
- throw;
- }
- }
Note: By default the FOR XML clause returns the column's values as attributes. The ELEMENTS parameter is added to the above SELECT statement to return the column's values as elements.
Summary
In this article, we learned how to read a SQL Server database table into a DataTable or DataSet and export data into an XML file and save it to a file.
Further Readings
Here are recommended articles: