c# - How to serialize/deserialize simple classes to XML and back -
Sometimes I want to store the data of my squares without setting the round trip for the database, for example, suppose I have the following classes:
Public category shoppingcart {public list & lt; CartItem & gt; Item {get; Set;} public at user id {received; Set; }} Public Class CartItem {Public Integrated Schuid {get; Set; } Receive the public int quantity; Set; } Public Double Extended Cast {get; Set; }}
Let me assume that I create a ShoppingCart
object in memory and want to "save" it as an XML document. Is this possible through some type of XDocument.CreateFromPOCO (shoppingcart)
method? How about other directions: An XML document such as new ShoppingCart (xDoc)
There is an inherent way of creating an object Div>
There is a way to do this. The second is Example with XmlSerializer
:
using System.Xml; Using System.Xml.Serialization; // ... shoppingcart shoppingcart = fetchShoppingCartFrom from somewhere (); Var serializer = New XmlSerializer (shoppingCart.GetType ()); (Using Var writer = XmlWriter.Create ("shoppingcart.xml")) {serializer.Serialize (author, shopping cart); }
and deserialize it back to:
var serializer = new XML sheller (shopping cart); (Var reader = XmlReader.Create ("shoppingcart.xml")) using {var shoppingCart = (ShoppingCart) serializer.Deserialize (reader); }
In addition to better encapsulation, I recommend you use properties instead of fields in your CartItem
category.
Comments
Post a Comment