Blogger Jeff = new Blogger

Programming and stuff in Western PA

Using Linq to query Xml

If you’ve used the .Net’s framework new Linq functionality, you’ve no doubt seen how nice it is to query a data object directly. For me, one of my favorite parts of Linq is being able to query an Xml object. Gone are the days are writing awkward XPath queries, or "ripping through" an Xml document.

Here’s the old school way of querying Xml :

static void OldSchool()
{ 
    string teams = @" " +
        "PhilliesNL" +
        "YankeesAL" +
        "AngelsAL" +
        "BrewersNL" +
        " ";

    XmlDocument xml = new XmlDocument();
    xml.LoadXml(teams);

    XmlNodeList NLTeams = xml.SelectNodes("//League[. = 'NL']/parent::node()/Name");

    foreach (XmlNode team in NLTeams)
        Console.WriteLine(team.InnerText);
}

And here’s the new school way :

static void NewSchool()
{
    XElement teams = XElement.Parse(@" " +
        "PhilliesNL" +
        "YankeesAL" +
        "AngelsAL" +
        "BrewersNL" +
        " ");
    
    IEnumerable NLTeams = from t in teams.Descendants("Team")
                   where t.Element("League").Value.Equals("NL")
                   select t.Element("Name").Value;

    foreach (var team in NLTeams)
        Console.WriteLine(team);
}

You’re pretty much writing the same amount of code, but the Linq way is more preferable in that it standardizes a way to query and object in .net for data.

Tags: , , ,

January 14, 2008 Posted by | .Net, C#, Linq, Technology, Xml | Leave a comment