zoukankan      html  css  js  c++  java
  • C#语言中的XmlSerializer类的XmlSerializer.Deserialize (Stream)方法举例详解

    包含由指定的 XML 文档反序列化 Stream

    命名空间:   System.Xml.Serialization
    程序集:  System.Xml(位于 System.Xml.dll)

    注意:

    反序列化是︰ 读取的 XML 文档,并构造对象强类型化到 XML 架构 (XSD) 文档的过程。

    在反序列化之前, XmlSerializer 必须使用要反序列化的对象的类型构造。

     下面举个例子说明:

    比如说有一个序列化后的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 + "	" +
          i.Description + "	" +
          i.UnitPrice + "	" +
          i.Quantity + "	" +
          i.LineTotal);
       }
    }
  • 相关阅读:
    Ubuntu 安装mysql和简单操作
    fatal error: mysql.h: No such file or directory
    彻底删除win10系统下的mysql
    ORACLE 回收站导致的故障
    Log Buffer
    ORACLE数据库存储结构
    Shared pool
    ORACLE 实例及RAC
    Buffer Cache
    数据库dump导入
  • 原文地址:https://www.cnblogs.com/yuanfg/p/8945400.html
Copyright © 2011-2022 走看看