.net - Serializing a list of Key/Value pairs to XML -
i have list of key/value pairs i'd store in , retrieve xml file. task similar described here. trying follow advice in marked answer (using keyvaluepair , xmlserializer) don't working.
what have far "settings" class ...
public class settings { public int simplevalue; public list<keyvaluepair<string, int>> list; }
... instance of 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));
... , following code write instance 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 pairs in list stored though number of elements correct. doing wrong. questions are:
- how can store key/value pairs of list in file?
- how can change default generated name "keyvaluepairofstringint32" of elements in list other name "listelement" i'd have?
keyvaluepair not serializable, because has read-only properties. here more information(thanks thomas levesque). changing generated name use [xmltype]
attribute.
define own this:
[serializable] [xmltype(typename="whatevernameyoulike")] public struct keyvaluepair<k, v> { public k key { get; set; } public v value { get; set; } }
Comments
Post a Comment