How to convert Linq query result to XML?

New to Linq to XML ...

I have a Linq query with results, and I would like to convert these results to XML. I suppose there should be a relatively easy way to do this, but I cannot find it ...

Thanks!

+7
c # linq linq-to-xml
source share
3 answers

Example. You should get this idea.

XElement xml = new XElement("companies", from company in db.CustomerCompanies orderby company.CompanyName select new XElement("company", new XAttribute("CompanyId", company.CompanyId), new XElement("CompanyName", company.CompanyName), new XElement("SapNumber", company.SapNumber), new XElement("RootCompanyId", company.RootCompanyId), new XElement("ParentCompanyId", company.ParentCompanyId) ) ); 
+9
source share

Your Linq query will return some kind of object graph; After you get the results, you can use any method to translate it into XML, which you could with standard objects. Linq to XML includes new XML classes that provide one way to create XML (see rAyt's answer for this), but you can also use the XmlSerializer and put attributes in your class / properties to control the exact XML result.

+1
source share

The following code will work for "linq for entities". Data must be in memory, made using .ToArray () for it to work, in a conversation.

 XElement xml = new XElement("companies", from company in db.CustomerCompanies.AsEnumerable() orderby company.CompanyName select new XElement("company", new XAttribute("CompanyId", company.CompanyId), new XElement("CompanyName", company.CompanyName), new XElement("SapNumber", company.SapNumber), new XElement("RootCompanyId", company.RootCompanyId), new XElement("ParentCompanyId", company.ParentCompanyId) ) ); 
+1
source share

All Articles