简体   繁体   中英

How do you transform a Linq query result to XML?

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!

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM