C#語言中的XmlSerializer類的XmlSerializer.Deserialize (Stream)方法舉例詳解

包含由指定的 XML 文檔反序列化 Stream架構

命名空間:   System.Xml.Serialization
程序集:  System.Xml(位於 System.Xml.dll)url

注意:spa

反序列化是︰ 讀取的 XML 文檔,並構造對象強類型化到 XML 架構 (XSD) 文檔的過程。.net

在反序列化以前, XmlSerializer 必須使用要反序列化的對象的類型構造。rest

 下面舉個例子說明:code

好比說有一個序列化後的xml文件,內容以下: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>

咱們能夠經過如下方法,把這個文件反序列化成一個OrderedItem類型的對象,看下面的例子:對象

using System; using System.IO; using System.Xml.Serialization; // This is the class that will be deserialized.
public class OrderedItem { [XmlElement(Namespace = "http://www.cpandl.com")] public string ItemName; [XmlElement(Namespace = "http://www.cpandl.com")] public string Description; [XmlElement(Namespace="http://www.cohowinery.com")] public decimal UnitPrice; [XmlElement(Namespace = "http://www.cpandl.com")] public int Quantity; [XmlElement(Namespace="http://www.cohowinery.com")] public decimal LineTotal; // A custom method used to calculate price per item.
   public void Calculate() { LineTotal = UnitPrice * Quantity; } } public class Test { public static void Main() { Test t = new Test(); // Read a purchase order.
      t.DeserializeObject("simple.xml"); } private void DeserializeObject(string filename) { Console.WriteLine("Reading with Stream"); // Create an instance of the XmlSerializer.
      XmlSerializer serializer = 
      new XmlSerializer(typeof(OrderedItem)); // Declare an object variable of the type to be deserialized.
 OrderedItem i; using (Stream reader = new FileStream(filename, FileMode.Open)) { // Call the Deserialize method to restore the object's state.
          i = (OrderedItem)serializer.Deserialize(reader); } // Write out the properties of the object.
 Console.Write( i.ItemName + "\t" + i.Description + "\t" + i.UnitPrice + "\t" + i.Quantity + "\t" + i.LineTotal); } }
相關文章
相關標籤/搜索