Serialize an object to XElement and Deserialize it in memory

后端 未结 5 1641
旧巷少年郎
旧巷少年郎 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:43

    You can use XMLSerialization

    XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialization re-creates the object in its original state from the XML output. You can think of serialization as a way of saving the state of an object into a stream or buffer. For example, ASP.NET uses the XmlSerializer class to encode XML Web service messages

    and XDocument Represents an XML document to achieve this

       using System;
    using System.Linq;
    using System.Xml;
    using System.Xml.Linq;
    using System.Xml.Serialization;
    
    
    namespace ConsoleApplication5
    {
      public class Person
      {
        public int Age { get; set; }
        public string Name { get; set; }
      }
    
      class Program
      {
        static void Main(string[] args)
        {
    
          XmlSerializer xs = new XmlSerializer(typeof(Person));
    
          Person p = new Person();
          p.Age = 35;
          p.Name = "Arnold";
    
          Console.WriteLine("\n Before serializing...\n");
          Console.WriteLine(string.Format("Age = {0} Name = {1}", p.Age,p.Name));
    
          XDocument d = new XDocument();
          using (XmlWriter xw = d.CreateWriter())
            xs.Serialize(xw, p);
    
          // you can use LINQ on elm now
    
          XElement elm = d.Root;
    
          Console.WriteLine("\n From XElement...\n");
    
          elm.Elements().All(e => { Console.WriteLine(string.Format("element name {0} , element value {1}", e.Name, e.Value)); return true; });
    
          //deserialize back to object
          Person pDeserialized = xs.Deserialize((d.CreateReader())) as Person;
    
          Console.WriteLine("\n After deserializing...\n");
          Console.WriteLine(string.Format("Age = {0} Name = {1}", p.Age, p.Name));
    
          Console.ReadLine();
    
        }
      }
    
    
    }
    

    and here is output enter image description here

提交回复
热议问题