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

  1. Casey says:

    Your explanation is awesome but my xml file is alittle more in depth but still similar how would I parse this in xml to linq

    I have lots of xml files to parse and I thought xml to linq was best way. Here is what part of the xml file looks like:

    <XAxisCalib
    <Max 288.93</Max
    <Min-48.08</Min
    <DfTHt0
    <LdVe0</LdVe
    <EjVe0</EjVe
    </XAxisCalib

    <YAxisCalib
    <Max 646.01</Max
    <Min -90.9</Min
    <DfTH0</DfTHt
    <LdVe0</LdVe
    <EjVe0</EjVe
    </YAxisCalib

    <ZAxisCalib
    <Max 16.1</Max
    <Min -146.82</Min
    <DfTHt0</DfTHt
    <LdVe0</LdVe
    <EjVe0</EjVe

    I need to extract out the "max" and "min" value of each of the X, Y, and Z AxisCalib. Can anyone help with this please.

  2. Casey says:

    Your explanation is awesoem but my xml file is alittle more in depth but still similar how would I parse this in xml to linq

    I have lots of xml files to parse and I thought xml to linq was best way. Here is what part of the xml file looks like:

    288.93
    -48.08
    0
    0
    0

    646.01
    -90.9
    0
    0
    0

    16.1
    -146.82
    0
    0
    0

    I need to extract out the “max” and “min” value of each of the X, Y, and Z AxisCalib. Can anyone help with this please.

  3. Sergio says:

    Nice article. One of the best LINQ to XML tutorials I have come across is here

    LINQ To XML Tutorials with Examples
    http://www.dotnetcurry.com/ShowArticle.aspx?ID=564

  4. Rod says:

    I love ur explanations- can u please extend this example to load an XML file into a strongly- typed customer object? It’s the part I don’t get in linq. Thanks!

  5. Duncan Watts says:

    @Dan Robbins that still sounds quite dirty! I wrote an extension method that checked if the XAttribute was null before returning the value and a set of overloads for defaults of various types.

  6. @Dan Robbins +1, this is an easy trap to fall into, particularly when you’re working with XML that isn’t schema-validated. I do kinda wish they had violated the design guidelines though and used implicit conversions.

  7. Dan Robbins says:

    Thanks for the good article. One note- I’ve found that using the .Value property can lead to null reference exceptions when the attribute or element is not found. I like to use the explicit conversions ( (string) or (int?) for example) – and ?? if I need to specify a default value.

Comments are closed.