Saturday, July 27, 2013

Create xml from database using LINQ

Create XML from Database

Suppose we have below table in database. Now I want to make xml of all the products which have stock greater than 0. Here I am using LINQ Pad to query data from the database. It is a great tool to query data from database using LINQ to SQL, LINQ to XML, LINQ to Entity Framework.
  1. CREATE TABLE Product (
  2. ProductID int IDENTITY(1,1) NOT NULL,
  3. ProductName varchar(50) NOT NULL,
  4. Price float NOT NULL,
  5. Stock int NOT NULL
  6. )
  7. GO
  8. INSERT INTO Product (ProductName,Price,Stock)VALUES('P001',12.12,100)
  9. INSERT INTO Product (ProductName,Price,Stock)VALUES('P002',102.12,200)
  10. INSERT INTO Product (ProductName,Price,Stock)VALUES('P003',104.12,500)
  11. INSERT INTO Product (ProductName,Price,Stock)VALUES('P004',108.12,100)
  12. INSERT INTO Product (ProductName,Price,Stock)VALUES('P005',72.12,10)
  13. INSERT INTO Product (ProductName,Price,Stock)VALUES('P006',72.12,0)
  14. GO
  15. SELECT * FROM Product

Now, query the data from above table using LINQ. We can also save the output to xml file.

  1. //Export above xml to xmlfile
  2. XElement.Save(Server.MapPath(@"~/export.xml"));

No comments:

Post a Comment