Tuesday, 23 May 2017

XDocument with linq

Now rather than using leveraging the XmlDocument functions for querying our xml document we can use linq with the XDocument to query our data.

<?xml version="1.0" encoding="utf-8" ?>
<people>
  <person firstname="john" lastname="doe">
    <contactdetails>
      <emailaddress>john@unknown.com</emailaddress>
      <phonenumber>9179799105</phonenumber>
    </contactdetails>
  </person>
  <person firstname="jane" lastname="doe">
    <contactdetails>
      <emailaddress>jane@unknown.com</emailaddress>
    </contactdetails>
  </person>
  <person firstname="tomek" lastname="chooch">
    <contactdetails>
      <emailaddress>tchooch@unknown.com</emailaddress>
    </contactdetails>
  </person>
  <person firstname="pawel" lastname="chooch">
    <contactdetails>
      <emailaddress>pchooch@unknown.com</emailaddress>
    </contactdetails>
  </person>
  <person firstname="magda" lastname="tyvoniuk">
    <contactdetails>
      <emailaddress>mt@unknown.com</emailaddress>
    </contactdetails>
  </person>
  <person firstname="adam" lastname="chooch">
    <contactdetails>
      <emailaddress>mt@unknown.com</emailaddress>
    </contactdetails>
  </person>
  <person firstname="jake" lastname="tyvoniuk">
    <contactdetails>
      <emailaddress>jt@unknown.com</emailaddress>
    </contactdetails>
  </person>

</people>

now let's load it into our XDocument and use linq to find what we want.

using System;
using System.Linq;
using System.Xml.Linq;

namespace pc.xmlDocumentExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var xDoc = XDocument.Load(@"..\..\data.xml");

            var choochs = xDoc.Descendants("person")
                .Where(p => p.LastAttribute.Value == "chooch")
                .OrderBy(p => p.FirstAttribute.Value);

            foreach (var c in choochs)
                Console.WriteLine(c);
        }
    }
}

again it comes at a performance price, but when dealing with smaller xml files may very well be trivial.