Created
February 6, 2012 10:12
-
-
Save refractalize/1751260 to your computer and use it in GitHub Desktop.
serializing key value pairs in a dictionary with System.Xml.Serialization.XmlSerializer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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