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)
)
);
Console.WriteLine(_customers);
The output will look like.
<customers>
<customer ID="1">
<name>Debajyoti</name>
<phone>123-123-1237</phone>
</customer>
<customer ID="2">
<name>Sumitra</name>
<phone>123-123-1236</phone>
</customer>
<customer ID="3">
<name>Wriju</name>
<phone>123-123-1235</phone>
</customer>
<customer ID="4">
<name>Writam</name>
<phone>123-123-1234</phone>
</customer>
</customers>
Isn’t it cool!!!! Yes, yes, yes….
Namoskar
Comments
Anonymous
March 12, 2008
was useful.. but i need more light on how to use LINQ to generate xml doc from db tablesAnonymous
March 13, 2008
@Kapil, Please visit, http://blogs.msdn.com/wriju/archive/2008/02/18/linq-to-xml-creating-complex-xml-through-linq.aspx On how to create XML from db.Anonymous
April 18, 2011
your code is not workingAnonymous
December 20, 2012
Nice query. It really helpful.