Beautiful LINQ to Xml

Is there anything better in life than finding a better way to do something? An easier commute, a better night’s sleep, a tastier cake recipe?

In starting the Nike+ importer for, I knew I was going to have to deal with a bit of XML. Which used to mean XPath.

Not so much anymore. LINQ to XML, you rock my world. It turns XML like this…

	<extendedData dataType="distance" intervalType="time" intervalUnit="s" intervalValue="10">
	0.0, 0.0372, 0.0705, 0.1041, ....
	<extendedData dataType="speed" intervalType="time" intervalUnit="s" intervalValue="10">
	0.0, 13.3866, 12.6856, 12.4970, ....
	<extendedData dataType="heartRate" intervalType="time" intervalUnit="s" intervalValue="10">
	0, 88, 108, 115, ....

With a little bit of code like this:

work.Snapshots = from n in extendedData.Elements("extendedData")
		 select new Workout.SnapShot
			 DataType = n.Attribute("dataType").Value,
			 Interval = (int) n.Attribute("intervalValue"),
			 IntervalType = n.Attribute("intervalType").Value,
			 IntervalUnit = n.Attribute("intervalUnit").Value,
			 Intervals = n.Value.Split(',').Select(p => Convert.ToSingle(p.Trim()))

into something useful. The best part – no more XPath string literals in your code. 2nd best part – that (int) cast. That isn’t really a cast – it’s actually an indirect call to Convert.ToInt32. So it parses the underlying value contained in the Attribute (or Element), then converts it into the correct type. That’s the kind of coding magic I like.


One thought on “Beautiful LINQ to Xml

  1. mmm… i just wrote this bitch..

    Me.Animals = From an In xDoc.Descendants(“STPR_STD_ANML”)
    Select New Animal With {
    .Id = an.Descendants(“ANML_NO”).Value,
    .Name = an.Descendants(“ANML_REF”).Value,
    .Sex = an.Descendants(“SEX”).Value,
    .StartDate = an.Descendants(“START_DATE”).Value,
    .BirthDate = an.Descendants(“BIRTH_DATE”).Value,
    .Group = xDoc.Descendants(“STPR_GRP”).Where(Function(a) a.Descendants(“ID”).Value = an.Descendants(“GRP_ID”).Value).Descendants(“GRP_NO”).Value,
    .Cage = xDoc.Descendants(“STPR_CAGE”).First(Function(a) a.Descendants(“ID”).Value = an.Descendants(“CAGE_ID”).Value).Value,
    .Selections = xDoc.Descendants(“STPR_SELN_CONTENTS”).Where(
    Function(a) a.Descendants(“STD_ANML_ID”).Value = an.Descendants(“ID”).Value).Select(
    Function(a) xDoc.Descendants(“STPR_SELN”).First(
    Function(b) b.Descendants(“ID”).Value = a.Descendants(“SELN_ID”).Value).Descendants(“NAME”).Value).ToList()

    so sexy 😉 would have take 100+ lines of code + loops before linq to xml.. 🙂

Leave a Reply

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

You are commenting using your 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