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 ...

Get C# 7 and .NET Core: Modern Cross-Platform Development - Second Edition 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.