views:

341

answers:

2

Newbie in the Linq to XML arena...

I have a Linq query with results, and I'd like to transform those results into XML. I'm guessing there must be a relatively easy way to do it, but I can't find it...

Thanks!

+5  A: 

An Example. You should get the 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)
                )
            );
Henrik P. Hessel
You need a .ToArray() in there.
blesh
why? I copied this from a project of mine.
Henrik P. Hessel
A: 

Your Linq query is going to return some kind of object graph; Once you have the results, you can use any method to translate it to XML that you could with standard objects. Linq to XML includes new XML classes that present one way of creating XML (see rAyt's answer for this), but you can also use an XmlSerializer and put attributes on your class/properties to control exact XML output.

Chris Shaffer