Linq to XML

A LINQ Tutorial

Earlier, we took a look at two variants on Linq statements, one against a collection of integers, and then another against a collection of user-defined objects (Customers).

Now, we’ll read an XML file and select from that with Linq.

To begin, we need to generate an XML file that can serve as our data source, just as the collection of customers did in the previous example.  To do this you can open a simple editor and create the following XML file (named Customer.xml).

<?xml version="1.0"  ?>
<Customers>
  <Customer
     FullName="George Washington"
     Address="The President's House"
     City="New York"
     State="NY"
     Phone="212-555-1212" />
  <Customer
     FullName="John Adams"
     Address="The White House"
     City="Washington"
     State="DC"
     Phone="202-555-1212" />
  <Customer
     FullName="Thomas Jefferson"
     Address="The White House"
     City="Washington"
     State="DC"
     Phone="202-555-1212" />
</Customers>

You can readily see that this is the same data we had in a collection previously.  Our job now is to read this file into the program and then to execute a Linq query against it.  Easy as cake.

To begin, create a new Windows Phone application and steal the Xaml for the Title Panel and Content Panel from the previous examples.  This gives you a TextBlock and a ListBox.

You will need to add a reference to System.Xml.Linq to your references, and a corresponding using statement in MainPage.xaml.cs.

Add the Customer.xaml file to your project and add the following line just below InitializeComponent in the constructor,

XDocument customers = XDocument.Load( "Customers.xml" );

That’s all it takes to load the file into your program.  You are ready, now to execute the query against the XML file.  This is only slightly trickier than the previous examples.  Here we must work our way to the appropriate element, which we do by asking the top element for its Descendants that are of type Customer

var query = from c in customers.Descendants( "Customer" )

We can now add a filter (a where statement) on the attribute City whose value is equal to Washington

where c.Attribute( "City" ).Value == "Washington"

If we want all the attributes in the matching lines in the XML file to be returned, we can now write

select c

But that is a lot of data to show in the list box, so we’ll create an anonymous object and specify which attributes we want

select new
{
   Name = c.Attribute( "FullName" ).Value,
   City = c.Attribute( "City" ).Value
};

We are now free to iterate through the results, adding each to the list box. Here is the complete code-behind page for context:

using System.Linq;
using System.Xml.Linq;
using Microsoft.Phone.Controls;

namespace LinqToXML
{
   public partial class MainPage : PhoneApplicationPage
   {
      public MainPage( )
      {
         InitializeComponent( );
         XDocument customers = XDocument.Load( "Customers.xml" );
         var query = from c in customers.Descendants( "Customer" )
                     where c.Attribute( "City" ).Value == "Washington"
                     select new
                     {
                        Name = c.Attribute( "FullName" ).Value,
                        City = c.Attribute( "City" ).Value
                     };

         foreach ( var cust in query )
            TheListBox.Items.Add( cust );
      }
   }
}

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Linq, Mini-Tutorial and tagged . Bookmark the permalink.

8 Responses to Linq to XML

Comments are closed.