How to read and write data using Linq to XML

Over the past few months I, like probably every other good MS dev on the planet, have been using Linq more and more to query data in my applications.  I’ve been using quite a lot of Linq to SQL in the data layer of my new Ambient Places website and a smaller amount to run simple queries over objects:

var countOfNonLetters = myString
     .Where(c => !Char.IsLetter(c))
     .Count() ;

It was only the other day when I was writing a small prototype app that I needed to use Linq to XML for the first time.  In the prototype I needed to load XML from disk, find some nodes, update the data, and then persist it back to disk.

First I read the document from disk and returned all nodes as strongly-typed elements within a List<T>:

public List<Place> GetAllLocations() {
    XElement doc = XElement.Load(fileName);

    var q = from location in doc.Descendants("location")
            select new Place(
                location.Attribute("name").Value,
                double.Parse(location.Attribute("latitude").Value),
                double.Parse(location.Attribute("longitude").Value)
                ) ;

    return q.ToList();
}

This code enumerates an IEnumerable of XElement and projects certain values from those items into a new type.  The resulting IEnumerable<Place> enumerable is then converted to an list and returned.

Adding a new element to the XML document and persisting it was equally as simple:

public void CreateLocation(string name, LatLong location) {

    XElement doc = XElement.Load(fileName);

    XElement newElem = new XElement(
        "location",
        new XAttribute("name", name),
        new XAttribute("latitude", location.Lat),
        new XAttribute("longitude", location.Lon)
        );

    doc.Add(new XElement[] {newElem}) ;
    doc.Save(fileName) ;
}

All of those horried CreateElement and AppendChild API calls gone and replaced with a much simpler API to deal with.

Very nice!

Advertisements

~ by D on October 31, 2007.

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 )

Google+ photo

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

Connecting to %s

 
%d bloggers like this: