Thursday, July 17, 2014

Swapping XML For YAML

I'm starting to write a simple utility program at work to make my life easier. As with all of these kind of things, I found myself needing somewhere to store my data to file, and I automatically thought of XML (I'm sure I'm not the only one).

Halfway through setting up serialization, I remembered a blog post I read a while back about alternatives to XML. Jeff Atwood wrote a piece about the Angle Bracket tax. This section in particular seems to jump out at me
1. Should XML be the default choice?
2. Is XML the simplest possible thing that can work for your intended use?
3. Do you know what the XML alternatives are?
4. Wouldn't it be nice to have easily readable, understandable data and configuration files, without all those sharp, pointy angle brackets jabbing you directly in your ever-lovin' eyeballs?
I realized I was defaulting to it. It wasn't the simplest thing for my use (at some point somebody may want to edit it by hand). I didn't know what the alternatives were, and it would be nice to be able to read it easily.

I read the whole post, so I guess by that point I did know what the alternatives were, but I decided to give YAML a shot. YAML stands for YAML Ain't Markup Language. It's like a more human-readable XML.

After a little research I came across YAMLSerializer for .NET, which did exactly what it said it would (thanks Nuget). With the following code -
        YamlSerializer serializer = new YamlSerializer();
        serializer.SerializeToFile("filename.yaml", obj);

I got exactly what I wanted -
%YAML 1.2
---
!Patcher.Patches
PatchList:
  ICollection.Items:
    - DateCreated: 2014-07-16 01:50:53.542Z
      Filename: Lighting v2.2.1.35.dll
      IgnorePatch: False
      FilenameFull: C:\Users\Chris\Google Drive\Programming\Microsoft\Patch Information\Patches\Lighting v2.2.1.35.dll
      IsFolder: False
      Revision: 2.2.1.35
      Destination: null
      Extension: "2"
    - DateCreated: 2014-07-16 01:51:10.300Z
      Filename: Lighting.dll
      IgnorePatch: False
      FilenameFull: C:\Users\Chris\Google Drive\Programming\Microsoft\Patch Information\Patches\Lighting.dll
      IsFolder: False
      Revision: 2.2.1.38
      Destination: C:\Bin\
      Extension: dll
...
Beautiful.

What's that? You want to load it back in? Here it is -
        YamlSerializer serializer = new YamlSerializer();
        obj = serializer.DeserializeFromFile("filename.yaml")[0];

Count me as a fan.

No comments:

Post a Comment