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
Open the console application project or folder named Ch09_Projection
.
In the Program.cs
file, import the System.Xml.Linq
namespace.
In the Main
method, at the bottom, write the following statements:
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());
Run the console application and view the output.
Note the structure of the XML generated matches the elements and attributes that the LINQ to XML statement declaratively described in the preceding code:
<products> <product id="1" price="18.0000"> <...