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

Reading XML by using LINQ to XML

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:

  • Load the XML file.
  • Use LINQ to XML to search for an element named appSettings, and its descendants named add.
  • Project the XML into an array of an anonymous type with a Key and Value property.
  • Enumerate through the array to show the results.
    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
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.151