Introduction
Using this simple code, you can generate XML files from database tables. XML files are very useful when it comes to transport data on the wire as they are platform independent. LINQ gives us a very simple way to generate XML files.
Using the Code
I have shown the code to generate the XML file from a database table tbl_Employee
. Let us have a look at the code briefly:
XElement
– This class loads and parses the XML. - The
string
“Employees
” is the root of the XML. empList in dt.AsEnumerable
– dt
is the datatable that has the employee
details, we convert it to Enumerable
and empList
is used like an alias. Select
query is pretty straight forward. “Employee
” is the tag name of the individual elements. XAttribute
indicates the attributes. Hence, here salary
and designation
are the attributes for Employee
tag. EmployeeName
and Designation
are child elements for Employee
element. - To save this XML on the disk, remove
.ToString()
and append .Save(<your>)</your>
<your>. For example .Save(“D://LINQ”)
string s= new XElement("Employees",
from empList in dt.AsEnumerable()
orderby empList.Field<decimal>("ESalary") descending
select new XElement("Employee",
new XAttribute("EmployeeId", empList.Field<Int32>("EID")),
new XAttribute("Salary", empList.Field<decimal>("ESalary")),
new XElement("EmployeeName", empList.Field<string>("EName")),
new XElement("Designation", empList.Field<string>("EDesignation"))
)).ToString()
You can refer to the attached code. It is a simple Windows form that fetches data from SQL server DB and displays it in XML format in the textbox.