XLinq: Create XML from object using LINQ


We have seen how to create the XML content from raw data initializing elements and attributes one by one. More realistic approach in the world of application development would be to read the values either from relational database or collection. Let’s use the combined power of LINQ and XLinq to create XML content easily and smartly.


Using C# 3.0 enhancement, implicitly typed array which is the combination of anonymous object initializers to create the anonymously typed data structures.

My famous Customers object, defined


var objCust = new[]


 new {CustID = 2, CustName = "Sumitra", Phone = "123-123-1236"},

 new {CustID = 3, CustName = "Wriju", Phone = "123-123-1235"},

 new {CustID = 4, CustName = "Writam", Phone = "123-123-1234"},

 new {CustID = 1, CustName = "Debajyoti", Phone = "123-123-1237"}



Now we will create XML out of it with proper order (notice that the CustID is not in proper sequence). We can filter the data with the help of LINQ.


XElement _customers = new XElement("customers",

                        from c in objCust

                        orderby c.CustID //descending

                        select new XElement("customer",

                            new XElement("name", c.CustName),

                            new XAttribute("ID", c.CustID),

                            new XElement("phone", c.Phone)






The output will look like.



  <customer ID="1">




  <customer ID="2">




  <customer ID="3">




  <customer ID="4">






Isn’t it cool!!!! Yes, yes, yes….