XmlSerializer序列化

/*XML 序列化是将对象的公共属性和字段转换为序列格式(这里是指 XML)以便存储或传输的过程。 
 * 反序列化则是从 XML 输出中重新创建原始状态的对象。 可以将序列化视为将对象的状态保存到
 * 流或缓冲区的方法。 例如,ASP.NET 使用 XmlSerializer 类对 XML Web services 
 * 消息进行编码。
 * 对象中的数据是用编程语言构造来描述的,如类、字段、属性、基元类型、数组,甚至 XmlElement
 * 或 XmlAttribute 对象形式的嵌入 XML。 您可以创建自己的用特性批注的类,或使用 
 * XML Schema Definition Tool (Xsd.exe) 生成基于现有 XML 架构定义 (XSD) 文档的类。
 * 如果有 XML 架构,则可以运行 XSD.exe 产生一组类,将这组类的类型强声明为此架构,并用特性
 * 批注这些类以便在序列化时遵循此架构。在对象和 XML 之间传输数据需要从编程语言构造到 XML 
 * 架构的映射和从 XML 架构到编程语言构造的映射。 XmlSerializer 和相关工具(如 Xsd.exe)
 * 在设计时和运行时都能在这两种技术之间提供一个桥梁。 在设计时,使用 Xsd.exe 可从自定义类产生
 * XML 架构文档 (.xsd) 或从给定架构产生类。 不论何种情况,这些类都用自定义特性进行批注,以指示
 * XmlSerializer 如何在 XML 架构系统和公共语言运行时之间映射。 在运行时,可以将这些类的实例
 * 序列化到遵循给定架构的 XML 文档中。 同样,可以将这些 XML 文档反序列化到运行时对象中。 注意,
 * XML 架构是可选的,在设计时或运行时不是必需的。控制生成的 XML为控制所生成的 XML,可以向类和
 * 成员应用特殊特性。 例如,为指定不同的 XML 元素名称,可以将 XmlElementAttribute 应用于
 * 公共字段或属性,同时设置 ElementName 属性。 有关类似特性的完整列表,请参见 
 * Attributes That Control XML Serialization。 也可以实现 IXmlSerializable 
 * 接口以控制 XML 输出。如果所生成的 XML 必须符合万维网联合会 (www.w3.org) 文档“简单对象访
 * 问协议 (SOAP) 1.1”的第 5 部分,则必须利用 XmlTypeMapping 构造 XmlSerializer。 
 * 若要进一步控制编码后的 SOAP XML,请使用 Attributes That Control Encoded SOAP Serialization
 * 中所列的特性。有了 XmlSerializer,可以利用使用强类型类的优点并仍具有 XML 的灵活性。 
 * 通过在强类型类中使用类型为 XmlElement、 XmlAttribute 或 XmlNode 的字段或属性,
 * 可以将部分 XML 文档直接读入 XML 对象中。如果使用扩展 XML 架构,则也可以使用 
 * XmlAnyElementAttribute 和 XmlAnyAttributeAttribute特性来序列化及反序列化在原始架构
 * 中找不到的元素或特性。 若要使用这些对象,请将 XmlAnyElementAttribute 应用到返回
 * XmlElement 对象数组的字段中,或者将 XmlAnyAttributeAttribute 应用到返回 
 * XmlAttribute 对象数组的字段中。如果属性或字段返回一个复杂对象(如数组或类实例),
 * 则 XmlSerializer 将其转换为嵌套在主 XML 文档内的元素。 例如,以下代码中的第一个类返回第二个类的实例。
 */
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

/* The XmlRootAttribute allows you to set an alternate name 
   (PurchaseOrder) of the XML element, the element namespace; by 
   default, the XmlSerializer uses the class name. The attribute 
   also allows you to set the XML namespace for the element.  Lastly,
   the attribute sets the IsNullable property, which specifies whether 
   the xsi:null attribute appears if the class instance is set to 
   a null reference. */
[XmlRootAttribute("PurchaseOrder", Namespace = "http://www.cpandl.com",
IsNullable = false)]
public class PurchaseOrder
{
    public Address ShipTo;
    public string OrderDate;
    /* The XmlArrayAttribute changes the XML element name
     from the default of "OrderedItems" to "Items". */
    [XmlArrayAttribute("Items")]
    public OrderedItem[] OrderedItems;
    public decimal SubTotal;
    public decimal ShipCost;
    public decimal TotalCost;
}

public class Address
{
    /* The XmlAttribute instructs the XmlSerializer to serialize the Name
       field as an XML attribute instead of an XML element (the default
       behavior). */
    [XmlAttribute]
    public string Name;
    public string Line1;

    /* Setting the IsNullable property to false instructs the 
       XmlSerializer that the XML attribute will not appear if 
       the City field is set to a null reference. */
    [XmlElementAttribute(IsNullable = false)]
    public string City;
    public string State;
    public string Zip;
}

public class OrderedItem
{
    public string ItemName;
    public string Description;
    public decimal UnitPrice;
    public int Quantity;
    public decimal LineTotal;

    /* Calculate is a custom method that calculates the price per item,
       and stores the value in a field. */
    public void Calculate()
    {
        LineTotal = UnitPrice * Quantity;
    }
}

public class Test
{
    public static void Main()
    {
        // Read and write purchase orders.
        Test t = new Test();
        t.CreatePO("po.xml");
        t.ReadPO("po.xml");
        Console.ReadLine();
    }

    private void CreatePO(string filename)
    {
        // Create an instance of the XmlSerializer class;
        // specify the type of object to serialize.
        XmlSerializer serializer =
        new XmlSerializer(typeof(PurchaseOrder));
        TextWriter writer = new StreamWriter(filename);
        PurchaseOrder po = new PurchaseOrder();

        // Create an address to ship and bill to.
        Address billAddress = new Address();
        billAddress.Name = "Teresa Atkinson";
        billAddress.Line1 = "1 Main St.";
        billAddress.City = "AnyTown";
        billAddress.State = "WA";
        billAddress.Zip = "00000";
        // Set ShipTo and BillTo to the same addressee.
        po.ShipTo = billAddress;
        po.OrderDate = System.DateTime.Now.ToLongDateString();

        // Create an OrderedItem object.
        OrderedItem i1 = new OrderedItem();
        i1.ItemName = "Widget S";
        i1.Description = "Small widget";
        i1.UnitPrice = (decimal)5.23;
        i1.Quantity = 3;
        i1.Calculate();

        // Insert the item into the array.
        OrderedItem[] items = { i1 };
        po.OrderedItems = items;
        // Calculate the total cost.
        decimal subTotal = new decimal();
        foreach (OrderedItem oi in items)
        {
            subTotal += oi.LineTotal;
        }
        po.SubTotal = subTotal;
        po.ShipCost = (decimal)12.51;
        po.TotalCost = po.SubTotal + po.ShipCost;
        // Serialize the purchase order, and close the TextWriter.
        serializer.Serialize(writer, po);
        writer.Close();
    }

    protected void ReadPO(string filename)
    {
        // Create an instance of the XmlSerializer class;
        // specify the type of object to be deserialized.
        XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
        /* If the XML document has been altered with unknown 
        nodes or attributes, handle them with the 
        UnknownNode and UnknownAttribute events.*/
        serializer.UnknownNode += new
        XmlNodeEventHandler(serializer_UnknownNode);
        serializer.UnknownAttribute += new
        XmlAttributeEventHandler(serializer_UnknownAttribute);

        // A FileStream is needed to read the XML document.
        FileStream fs = new FileStream(filename, FileMode.Open);
        // Declare an object variable of the type to be deserialized.
        PurchaseOrder po;
        /* Use the Deserialize method to restore the object's state with
        data from the XML document. */
        po = (PurchaseOrder)serializer.Deserialize(fs);
        // Read the order date.
        Console.WriteLine("OrderDate: " + po.OrderDate);

        // Read the shipping address.
        Address shipTo = po.ShipTo;
        ReadAddress(shipTo, "Ship To:");
        // Read the list of ordered items.
        OrderedItem[] items = po.OrderedItems;
        Console.WriteLine("Items to be shipped:");
        foreach (OrderedItem oi in items)
        {
            Console.WriteLine("\t" +
            oi.ItemName + "\t" +
            oi.Description + "\t" +
            oi.UnitPrice + "\t" +
            oi.Quantity + "\t" +
            oi.LineTotal);
        }
        // Read the subtotal, shipping cost, and total cost.
        Console.WriteLine("\t\t\t\t\t Subtotal\t" + po.SubTotal);
        Console.WriteLine("\t\t\t\t\t Shipping\t" + po.ShipCost);
        Console.WriteLine("\t\t\t\t\t Total\t\t" + po.TotalCost);
    }

    protected void ReadAddress(Address a, string label)
    {
        // Read the fields of the Address object.
        Console.WriteLine(label);
        Console.WriteLine("\t" + a.Name);
        Console.WriteLine("\t" + a.Line1);
        Console.WriteLine("\t" + a.City);
        Console.WriteLine("\t" + a.State);
        Console.WriteLine("\t" + a.Zip);
        Console.WriteLine();
    }

    private void serializer_UnknownNode
    (object sender, XmlNodeEventArgs e)
    {
        Console.WriteLine("Unknown Node:" + e.Name + "\t" + e.Text);
    }

    private void serializer_UnknownAttribute
    (object sender, XmlAttributeEventArgs e)
    {
        System.Xml.XmlAttribute attr = e.Attr;
        Console.WriteLine("Unknown attribute " +
        attr.Name + "='" + attr.Value + "'");
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值