LINQ to XML is a LINQ provider that allows you to query and manipulate 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"> <name>Chai</name> </product> <product id="2" price="19.0000"> <name>Chang</name> </product> <product id="3" price="10.0000"> <name>Aniseed Syrup</name> </product>
You might want to use LINQ to XML to easily query XML files.
In the Ch09_Projection
project, add an XML file named settings.xml
. Modify its contents to look like this:
<?xml version="1.0" encoding="utf-8" ?> <appSettings> <add key="color" value="red" /> <add key="size" value="large" /> <add key="price" value="23.99" /> </appSettings>
Back in the Program
class, add the following statements to:
appSettings
, and its descendants named add
.Key
and Value
property.XDocument doc = XDocument.Load("settings.xml"); var appSettings = doc.Descendants( "appSettings").Descendants("add") .Select(node => new { Key = node.Attribute("key").Value, Value = node.Attribute("value").Value }) .ToArray(); foreach (var item in appSettings) { WriteLine($"{item.Key}: {item.Value}"); }
Run the console application and view the output:
color: red size: large price: 23.99
3.139.83.151