Wednesday, March 18, 2009

Xml cleanup fun (thanks to linq)

Today at work I got to clean up some xml handling code I had written a while back. Here are the versions that came out.

using System.Xml;

// original code fragment
XmlElement el;

el = xdoc.CreateElement("name1", xdoc.DocumentElement.NamespaceURI);
el.InnerText = "some value gathered from environment";
root.AppedChild(el);

el = xdoc.CreateElement("name2", xdoc.DocumentElement.NamespaceURI);
el.InnerText = "some value gathered from environment";
root.AppedChild(el);

// ... and so on
using System.Xml.Linq;

// using linq

root.Add(new XElement(ns + "name1", "some value from the environment"));
root.Add(new XElement(ns + "name1", "some value from the environment"));

// ... and so on
using System.Xml.Linq;

// using linq AND getting fancy. Made things much more readable IMHO
Action<string,string> f = (n,v) => root.Add(new XElement(ns + n, v));

f("name1", "some value from the environment");
f("name1", "some value from the environment");

// ... and so on

Beautiful! The list of entries was quite large, so the noise prunnning looked more significant in my code. Things you end up doing after you use Haskell's where.

No comments: