LINQ

LINQ to the Rescue

A friend needed a quick way to query an existing XML file for certain values from within a .NET project. So, I suggested he use LINQ (Language Integrated Query). It’s simple enough. Though LINQ has been around for awhile, many developers still believe it is only useful to query SQL databases. LINQ can query SQL, XML, and even generic data structures like lists and queues.  Check out PLINQ (Parallel LINQ) for even more power.

Back to my friend’s problem…

Here’s an example XML file:

<?xml version="1.0" encoding="utf-8" ?>
<Books>
  <Book Title ="The Hunt for Red October" Author ="Clancy"/>
  <Book Title ="Huckleberry Finn" Author ="Twain"/>
  <Book Title ="Rainbow Six" Author ="Clancy"/>
  <Book Title ="The Call of the Wild" Author ="London"/>
</Books>

And, now the code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Windows.Forms;

namespace LINQ
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            test();
        }

        public void test()
        {
            XDocument books = XDocument.Load(@"../../books.xml");
            var xml = from x in books.Descendants("Book")
                      where x.Attribute("Author").Value == "Clancy"
                      select x;

            foreach (var x in xml)
            {
                Console.WriteLine(x);
            }
        }
    }
}

And, here's the output:
<Book Title="The Hunt for Red October" Author="Clancy" />
<Book Title="Rainbow Six" Author="Clancy" />

No comments yet... Be the first to leave a reply!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.