C#语言中的XmlSerializer类的XmlSerializer.Serialize(Stream,Object)方法举例详解
在对象和 XML 文档之间进行序列化和反序列化操作。 XmlSerializer 使您能够控制如何将对象编码为 XML。
命名空间: System.Xml.Serialization
程序集: System.Xml(位于 System.Xml.dll)
下面举个例子说明:
// This is the class that will be serialized. public class OrderedItem { public string ItemName; public string Description; public decimal UnitPrice; public int Quantity; public decimal LineTotal; // A custom method used to calculate price per item. public void Calculate() { LineTotal = UnitPrice * Quantity; } }
如何把这个类转换成一个xml文件呢,这时候就需要 XmlSerializer类来处理了。
它的Serialize(Stream, Object)这个方法,就是用来把一个user类的对象转换成xml文档的。
我们来看一个例子:
using System; using System.IO; using System.Xml.Serialization;public class Test{ public static void Main(string[] args) { Test t = new Test(); // Write a purchase order. t.SerializeObject("simple.xml"); } private void SerializeObject(string filename) { Console.WriteLine("Writing With Stream"); XmlSerializer serializer = new XmlSerializer(typeof(OrderedItem)); OrderedItem i = new OrderedItem(); i.ItemName = "Widget"; i.Description = "Regular Widget"; i.Quantity = 10; i.UnitPrice = (decimal) 2.30; i.Calculate(); // Create a FileStream to write with. Stream writer = new FileStream(filename, FileMode.Create); // Serialize the object, and close the TextWriter serializer.Serialize(writer, i); writer.Close(); } }
所生成的xml文件如下格式:
<?xml version="1.0"?> <OrderedItem xmlns:inventory="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com"> <inventory:ItemName>Widget</inventory:ItemName> <inventory:Description>Regular Widget</inventory:Description> <money:UnitPrice>2.3</money:UnitPrice> <inventory:Quantity>10</inventory:Quantity> <money:LineTotal>23</money:LineTotal> </OrderedItem>