Hallo,
möchte eine Klasse als XML Dokument speichern.
Hab im Internet gelesen das man dictonarys nicht umwandeln kann.
Hat jemand eine Idee ?
Danke für jeden Tip
[Serializable]
public class Status
{
String _Name;
public Status(String Name)
{
_Name = Name;
}
public Status() { }
public String Name
{
get
{
return _Name;
}
}
/// [XmlIgnore]
public Dictionary<String, IVSElement> elements = new Dictionary<String, IVSElement>() ;
}
public interface IVSElement
{
}
[Serializable]
public class VSE<Type> : IVSElement
{
public ViewStatusElement(Type v)
{
this.Value = v;
}
public Type Value;
}
So möchte ich Serialisieren :
Status VS;
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(vs.GetType());
x.Serialize(Console.Out, VS);
Bin im Internet auf folgendes gestpßen:
public static class SerializationExtensions
{
public static string Serialize<T>(this T obj)
{
var serializer = new DataContractSerializer(obj.GetType());
using (var writer = new StringWriter())
using (var stm = new XmlTextWriter(writer))
{
serializer.WriteObject(stm, obj);
return writer.ToString();
}
}
public static T Deserialize<T>(this string serialized)
{
var serializer = new DataContractSerializer(typeof(T));
using (var reader = new StringReader(serialized))
using (var stm = new XmlTextReader(reader))
{
return (T)serializer.ReadObject(stm);
}
}
}
This works perfectly in .NET 4 and should also work in .NET 3.5, although I didn't test it yet. I did the streaming to string because it was more convenient to me, although I could have introduced a lower-level serialization to Stream and then used it to serialize to strings, but I tend to generalize only when needed (just like premature optimization is evil, so it is premature generalization...)
Usage is very simple:
// dictionary to serialize to string
Dictionary<string, object> myDict = new Dictionary<string, object>();
// add items to the dictionary...
myDict.Add(...);
// serialization is straight-forward
string serialized = myDict.Serialize();
...
// deserialization is just as simple
Dictionary<string, object> myDictCopy =
serialized.Deserialize<Dictionary<string,object>>();
Leider fehlt mir die Verbindung zu meinem Code.
Möchte ja nicht nur das Dictonary speichern sondern die Klasse in der sich das Dictonary befindet.
Hallo,
der DataContractSerializer scheint das zu können. Ist das vllt. eine Alternative?
Sonst kannst Du auch mal nach
serializabledictionary
googlen. Dann kannst Du nur deine dictionary Variable in der Klasse einfach durch das SerializableDictionary tauschen.