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!
LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the . NET programming languages. LINQ to XML is like the Document Object Model (DOM) in that it brings the XML document into memory.
LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.
The LINQ to XML will bring the XML document into memory and allows us to write LINQ Queries on in-memory XML document to get the XML document elements and attributes. To use LINQ to XML functionality in our applications, we need to add "System. Xml. Linq" namespace reference.
By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.
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)
)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With