How to serialize/deserialize simple classes to XML and back

前端 未结 4 865
Happy的楠姐
Happy的楠姐 2020-11-28 10:22

Sometimes I want to emulate stored data of my classes without setting up a round trip to the database. For example, let\'s say I have the following classes:



        
相关标签:
4条回答
  • 2020-11-28 10:58

    You could serialize/deserialize with either the XmlSerializer or the DataContractSerializer.

    Annotate your classes with DataContract and DataMember attributes and write something like this to serialize to xml to a file.

    ShoppingCart cart = ...
    using(FileStream writer = new FileStream(fileName, FileMode.Create))
    {
       DataContractSerializer ser = new DataContractSerializer(typeof(ShoppingCart));
       ser.WriteObject(writer, cart);
    }
    
    0 讨论(0)
  • 2020-11-28 10:59

    Nicely done. Here is the example to serialize plain POCO to string.

        private string poco2Xml(object obj)
        {
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            StringBuilder result = new StringBuilder();
            using (var writer = XmlWriter.Create(result))
            {
                serializer.Serialize(writer, obj);
            }
            return result.ToString();
        }
    
    0 讨论(0)
  • 2020-11-28 11:01

    Just mark up what you want to serialize with [XmlElement(name)] (or XmlAttribute, XmlRoot, etc) and then use the XmlSerializer. If you need really custom formating, implement IXmlSerializable.

    0 讨论(0)
  • 2020-11-28 11:04

    XmlSerializer is one way to do it. DataContractSerializer is another. Example with XmlSerializer:

    using System.Xml;
    using System.Xml.Serialization;
    
    //...
    
    ShoppingCart shoppingCart = FetchShoppingCartFromSomewhere();
    var serializer = new XmlSerializer(shoppingCart.GetType());
    using (var writer = XmlWriter.Create("shoppingcart.xml"))
    {
        serializer.Serialize(writer, shoppingCart);
    }
    

    and to deserialize it back:

    var serializer = new XmlSerializer(typeof(ShoppingCart));
    using (var reader = XmlReader.Create("shoppingcart.xml"))
    {
        var shoppingCart = (ShoppingCart)serializer.Deserialize(reader);
    }
    

    Also for better encapsulation I would recommend you using properties instead of fields in your CartItem class.

    0 讨论(0)
提交回复
热议问题