Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

c# - How to serialize/deserialize simple classes to XML and back

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:

public class ShoppingCart
{
    public List<CartItem> Items {get; set;}
    public int UserID { get; set; }
}

public class CartItem
{
    public int SkuID { get; set; }
    public int Quantity  { get; set; }
    public double ExtendedCost  { get; set; }
}

Let's say I build a ShoppingCart object in memory and want to "save" it as an XML document. Is this possible via some kind of XDocument.CreateFromPOCO(shoppingCart) method? How about in the other direction: is there a built-in way to create a ShoppingCart object from an XML document like new ShoppingCart(xDoc)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...