How to read XML file in C#

Suppose that the user has to read the XML file he/she already generated. The application should provide functionality to extract all vendors from Canada, and after that the user has to process them in alphabetic order.

C# in Depth, 3rd EditionManaged Windows VPS Hosting

 

Web developer has to follow these steps:
   1.Create the XDocument using the XML.
   2.Navigate the XElement elements to reach the Vendor ones.
   3.Take the XElement instances that have a child XElement whose name is Country and whose value is Canada.

The following C# code lines illustrate how to perform filtering

var mydoc = XDocument.Load(path);
var canada = mydoc.Root.Elements(“Vendor”)
   .Where(c => c.Element(“Country”).Value == “Canada”)
   .Select(c =>
      new
      {
         Name = c.Element(“Name”).Value,
         Country = c.Element(“Country”).Value
      }
   );

The Root property of the XDocument object represents the root node, and the Elements property gives access to the children of the root (Vendor). Web developer then filters them using a lambda expression. Note: The lambda expression code isn’t strongly typed because Web developer is working with XML, which is a loose-typed data format.

The next C# code lines show how to sort Vendors by name, using the OrderBy method:

var sorted = mydoc.Root.Elements(“Vendor”)
   .OrderBy(c => c.Element(“Name”).Value)
   .Select(c =>
     new
     {
        Name = c.Element(“Name”).Value,
        Country = c.Element(“Country”).Value
     }
   );