Home > Articles > Web Services > XML

  • Print
  • + Share This
From the author of

Programming with LINQ to XSD

Now you have strongly typed classes and XML data. To use LINQ with the XML data, all you need to do is load the XML file and write some LINQ queries, as demonstrated in Listing 3.

Listing 3 Querying the XML data with the generated classes.

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Linq;


namespace LINQToXsdDemo
{
 class Program
 {
  static void Main(string[] args)
  {
   var data = Root.Load("../../Data.xml");

   var customers = from customer in data.Customer
           select new
           {
            CustomerName = customer.CompanyName,
            ContactName = customer.ContactName,
            Phone = customer.Phone
           };

   Array.ForEach(customers.ToArray(), x => Console.WriteLine(x));
   Console.ReadLine();
  }
 }
}

The only significant difference between the code in Listing 3 and regular LINQ to Objects code is that the data resides in an .XML file. Once the data is loaded, write whatever LINQ query you need. In the listing, data becomes the root type defined by the XML; this means that there's a code-generated class that in this case happens to be Root (literally).

The LINQ query returns an iteratable collection of the projected type, which includes the CustomerName, ContactName, and Phone. The Array.ForEach statement depends on the result of the LINQ query and a Lambda expression that uses the default ToString behavior to print each object.

  • + Share This
  • 🔖 Save To Your Account