Serialization and deserialization. To write this article I was using this web page. First lets serialize the XML. Idea is to create xml like
<?xml version="1.0" encoding="utf-8"?> <definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <channels> <channel> <urn>test</urn> </channel> </channels> </definitions>
So, first we have to prepare model, and looks like:
public class definitions { public List<channel> channels { get; set; } } public class channel { public string urn { get; set; } }
Now serialization:
definitions serializeObject = new definitions(); channel channel = new channel(); channel.urn = "test"; serializeObject.channels = new List<channel>(); serializeObject.channels.Add(channel); XmlSerializer xmlSerializer = new XmlSerializer(typeof(definitions)); TextWriter txtWriter = new StreamWriter(@"d:\temp\MyTest.xml"); xmlSerializer.Serialize(txtWriter, serializeObject); txtWriter.Close();
That is all about serialization. Now we well deserialize same XML:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(definitions)); using (FileStream fileStream = File.OpenRead(@"d:\temp\MyTest.xml")) { definitions channelDefinitions = (definitions)xmlSerializer.Deserialize(fileStream); ChannelModels = channelDefinitions.channels; }
Example project you can download from here.
That's all folks!