Working with LINQ to XML
LINQ to XML is a provider that allows you to use LINQ to query and manipulate XML.
Generating XML using LINQ to XML
Add a new console application project named Ch09_LINQandXML. Add a new ADO.NET Entity Data Model item named Northwind
. Use Code First from database, connect to the Northwind
database on the server named (localdb)\mssqllocaldb
, and select all the tables.
Import System.Xml.Linq
. In the Main
method, write the following statements:
var db = new Northwind(); var products = db.Products.ToArray(); var xml = new XElement("products", from p in products select new XElement("product", new XAttribute("id", p.ProductID), new XAttribute("price", p.UnitPrice), new XElement("name", p.ProductName))); Console.WriteLine(xml.ToString());
Run the application. Notice that the structure of the XML generated matches the elements and attributes that the LINQ to XML statement declaratively...