Working with LINQ to XML
LINQ to XML is a LINQ provider that allows you to query and manipulate XML.
Generating XML using LINQ to XML
Let's create a method to convert the Products
table into XML.
- In
Program.cs
, import theSystem.Xml.Linq
namespace. - Create a method to output the products in XML format, as shown in the following code:
static void OutputProductsAsXml() { using (var db = new Northwind()) { var productsForXml = db.Products.ToArray(); var xml = new XElement("products", from p in productsForXml select new XElement("product", new XAttribute("id", p.ProductID), new XAttribute("price", p.UnitPrice), new XElement("name", p.ProductName))); WriteLine(xml.ToString()); } }
- In
Main
, comment the previous method call and callOutputProductsAsXml
. - Run the console application, view the result, and note that the structure of...