How do you transform a Linq query result to XML?

2019-04-26 22:20发布

问题:

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!

回答1:

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)
                )
            );


回答2:

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.



回答3:

The below code will work for "linq to entities". The data has to be in the memory, done with .ToArray(), in order to it to be worked on, in a matter of speaking.

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)
            )
        );