I have a list of key/value pairs I'd like to store in and retrieve from a XML file. So this task is similar as described here. I am trying to follow the advice in the marked answer (using a KeyValuePair and a XmlSerializer) but I don't get it working.
What I have so far is a "Settings" class ...
public class Settings { public int simpleValue; public List<KeyValuePair<string, int>> list; }
... an instance of this class ...
Settings aSettings = new Settings(); aSettings.simpleValue = 2; aSettings.list = new List<KeyValuePair<string, int>>(); aSettings.list.Add(new KeyValuePair<string, int>("m1", 1)); aSettings.list.Add(new KeyValuePair<string, int>("m2", 2));
... and the following code to write that instance to a XML file:
XmlSerializer serializer = new XmlSerializer(typeof(Settings)); TextWriter writer = new StreamWriter("c:\\testfile.xml"); serializer.Serialize(writer, aSettings); writer.Close();
The resulting file is:
<?xml version="1.0" encoding="utf-8"?> <Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <simpleValue>2</simpleValue> <list> <KeyValuePairOfStringInt32 /> <KeyValuePairOfStringInt32 /> </list> </Settings>
So neither key nor value of the pairs in my list are stored though the number of elements is correct. Obviously I am doing something basically wrong. My questions are:
XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.
Serialization is the process of converting an object into a form that can be readily transported. For example, you can serialize an object and transport it over the Internet using HTTP between a client and a server. On the other end, deserialization reconstructs the object from the stream.
As with the CreatePo method, you must first construct an XmlSerializer, passing the type of the class to be deserialized to the constructor. Also, a FileStream is required to read the XML document. To deserialize the objects, call the Deserialize method with the FileStream as an argument.
KeyValuePair is not serializable, because it has read-only properties. Here is more information(thanks to Thomas Levesque). For changing the generated name use the [XmlType]
attribute.
Define your own like this:
[Serializable] [XmlType(TypeName="WhateverNameYouLike")] public struct KeyValuePair<K, V> { public K Key { get; set; } public V Value { get; set; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With