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

Get C# 6 and .NET Core 1.0: Modern Cross-Platform Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.