简体   繁体   English

如何将Linq查询结果转换为XML?

[英]How do you transform a Linq query result to XML?

Newbie in the Linq to XML arena... Linq到XML领域的新手......

I have a Linq query with results, and I'd like to transform those results into XML. 我有一个带结果的Linq查询,我想将这些结果转换为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; 你的Linq查询将返回某种对象图; Once you have the results, you can use any method to translate it to XML that you could with standard objects. 获得结果后,您可以使用任何方法将其转换为可以使用标准对象的XML。 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. Linq to XML包含新的XML类,它提供了一种创建XML的方法(请参阅rAyt的答案),但您也可以使用XmlSerializer并在类/属性上放置属性来控制精确的XML输出。

The below code will work for "linq to entities". 以下代码适用于“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. 数据必须在内存中,使用.ToArray()完成,以便进行处理。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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