Serialize an object to XElement and Deserialize it in memory

后端 未结 5 1607
旧巷少年郎
旧巷少年郎 2020-12-04 13:15

I want to serialize an object to XML, but I don\'t want to save it on the disk. I want to hold it in a XElement variable (for using with LINQ), and then Deserialize back to

5条回答
  •  情深已故
    2020-12-04 13:26

    (Late answer)

    Serialize:

    var doc = new XDocument();
    var xmlSerializer = new XmlSerializer(typeof(MyClass));
    using (var writer = doc.CreateWriter())
    {
        xmlSerializer.Serialize(writer, obj);
    }
    // now you can use `doc`(XDocument) or `doc.Root` (XElement)
    

    Deserialize:

    MyClass obj; 
    using(var reader = doc.CreateReader())
    {
        obj = (MyClass)xmlSerializer.Deserialize(reader);
    }
    

提交回复
热议问题