Skip to content

Instantly share code, notes, and snippets.

@refractalize
Created February 6, 2012 10:12
Show Gist options
  • Save refractalize/1751260 to your computer and use it in GitHub Desktop.
Save refractalize/1751260 to your computer and use it in GitHub Desktop.
serializing key value pairs in a dictionary with System.Xml.Serialization.XmlSerializer
[TestFixture]
public class TrackXml {
[Test]
public void ShouldSerialiseKeyValuePairs() {
var xml = @"<track><title>Abracadabra</title><artist>Steve Miller Band</artist></track>";
var track = new Track();
track.Properties["title"] = "Abracadabra";
track.Properties["artist"] = "Steve Miller Band";
track.AssertSerializesAs(xml);
}
[Test]
public void ShouldDeserialiseKeyValuePairs() {
var xml = @"<track><title>Abracadabra</title><artist>Steve Miller Band</artist></track>";
var xser = new XmlSerializer(typeof (Track));
var actualTrack = (Track) xser.Deserialize(new StringReader(xml));
Assert.That(actualTrack.Properties["title"], Is.EqualTo("Abracadabra"));
Assert.That(actualTrack.Properties["artist"], Is.EqualTo("Steve Miller Band"));
Assert.That(actualTrack.Properties.Count, Is.EqualTo(2));
}
}
[XmlRoot("track")]
public class Track {
[XmlIgnore]
public Dictionary<string, string> Properties = new Dictionary<string, string>();
[XmlAnyElement]
public XElement[] XmlProperties {
get {
return Properties.Select(entry => new XElement(entry.Key, entry.Value)).ToArray();
}
set {
Properties = value.ToDictionary(el => el.Name.LocalName, el => el.Value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment