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 the
LinqWithEFCore
project, inProgram.Functions.cs
, import theSystem.Xml.Linq
namespace. - In
Program.Functions.cs
, add a method to output the products in XML format, as shown in the following code:static void OutputProductsAsXml() { SectionTitle("Output products as XML"); using (Northwind db = new()) { Product[] productsArray = db.Products.ToArray(); XElement xml = new("products", from p in productsArray select new XElement("product", new XAttribute("id", p.ProductId), new XAttribute("price", p.UnitPrice), new XElement("name", p.ProductName))); WriteLine(xml.ToString()); } }
- In
Program.cs
, call theOutputProductsAsXml...