This example demonstrate how to serialize and deserialize List<string> object to XML string and deserialize XML string to a List<string> object.
protected override void OnLoad(EventArgs e) { base.OnLoad(e); List<string> values = new List<string>(); for (int i = 0; i < 10; i++) values.Add("Value " + i); string xml = this.Serialize(values); /// /// Save database as XML so that you can do a XPath Query /// /// /// Get xml string and convert it in to a List<string> /// List<string> savedValues = this.Deserialize(xml); } private string Serialize(List<string> values) { XmlSerializer serializer = new XmlSerializer(typeof(List<string>)); MemoryStream stream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); serializer.Serialize(writer, values); stream = (MemoryStream)writer.BaseStream; UTF8Encoding utf8 = new UTF8Encoding(); string xml = utf8.GetString(stream.ToArray()); return xml; } private List<string> Deserialize(string xml) { XmlSerializer serializer = new XmlSerializer(typeof(List<string>)); UTF8Encoding utf8 = new UTF8Encoding(); byte[] bytes = utf8.GetBytes(xml); MemoryStream stream = new MemoryStream(bytes); XmlTextReader reader = new XmlTextReader(stream); List<string> values = (List<string>)serializer.Deserialize(reader); return values; }
No comments:
Post a Comment