301223 HOW TO:使用 XML 序列化进行对象读写 (From MKBA)

本文的发布号曾为 CHS301223
本文讨论一种 Microsoft 产品的 Beta 版本。本文中的信息按“原样”提供,如有更改恕不另行通知。

对于该 Beta 产品,Microsoft 不提供正式的产品支持。有关获取对 Beta 版本的支持的信息,请参阅 Beta 产品文件中包括的文档资料,或查看您下载此版本的站点。

本任务的内容

概要

本文演示如何使用 XML 序列化类将某个可扩展标记语言 (XML) 流自动映射到一组用于保存 XML 的对象。

返回页首

要求

下表概括了推荐使用的硬件、软件、网络架构以及所需的 Service Pack:
  • Microsoft Windows 2000 Professional、Windows 2000 Server、Windows 2000 Advanced Server 或 Windows NT 4.0 Server
  • Microsoft Visual Studio .NET
  • Xsd.exe 工具(包括在 Visual Studio .NET 和 .Net 框架 SDK 中,可在 /Program Files/Microsoft.NET/FrameworkSDK/Bin 或类似的位置找到该文件)
本文假定您熟悉下列主题:
  • 序列化概念
  • 创建和读取 XML
返回页首

如何将对象读写到 XML 中

  1. 创建可序列化的类,或者创建用于处理 XML 序列化类的类。 如果您拥有描述要加载或保存的 XML 文件格式的 XML 架构定义 (XSD),请使用 Xsd.exe 工具自动创建这些类。 还可以手动创建这些类。 若要使用 Xsd.exe 工具创建可序列化的类,请按照下列步骤操作:

    1. 将以下描述订单的 XSD 架构保存为 Po.xsd 文件:
      <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                  elementFormDefault="qualified"
                  targetNamespace="" >
      
       <xsd:annotation>
        <xsd:documentation>
         Purchase order schema for Example.com.
         Copyright 2000 Example.com. All rights reserved.
        </xsd:documentation>
       </xsd:annotation>
      
       <xsd:element name="purchaseOrder" type="PurchaseOrder" />
      
       <xsd:element name="comment" type="xsd:string"/>
      
       <xsd:complexType name="PurchaseOrder">
        <xsd:sequence>
         <xsd:element name="shipTo" type="USAddress"/>
         <xsd:element name="billTo" type="USAddress"/>
         <xsd:element ref="comment" minOccurs="0"/>
         <xsd:element name="items"  type="Items"/>
        </xsd:sequence>
        <xsd:attribute name="orderDate" type="xsd:date"/>
       </xsd:complexType>
      
       <xsd:complexType name="USAddress">
        <xsd:sequence>
         <xsd:element name="name"   type="xsd:string"/>
         <xsd:element name="street" type="xsd:string"/>
         <xsd:element name="city"   type="xsd:string"/>
         <xsd:element name="state"  type="xsd:string"/>
         <xsd:element name="zip"    type="xsd:decimal"/>
        </xsd:sequence>
        <xsd:attribute name="country" type="xsd:NMTOKEN" />
       </xsd:complexType>
      
       <xsd:complexType name="Items">
        <xsd:sequence>
         <xsd:element name="item" minOccurs="0" maxOccurs="unbounded">
          <xsd:complexType>
           <xsd:sequence>
            <xsd:element name="productName" type="xsd:string"/>
            <xsd:element name="quantity">
             <xsd:simpleType>
              <xsd:restriction base="xsd:positiveInteger">
               <xsd:maxExclusive value="100"/>
              </xsd:restriction>
             </xsd:simpleType>
            </xsd:element>
            <xsd:element name="USPrice"    type="xsd:decimal"/>
            <xsd:element ref="comment"   minOccurs="0"/>
            <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
           </xsd:sequence>
           <xsd:attribute name="partNum" type="SKU"/>
          </xsd:complexType>
         </xsd:element>
        </xsd:sequence>
       </xsd:complexType>
      
       <xsd:simpleType name="SKU">
        <xsd:restriction base="xsd:string">
         <xsd:pattern value="/d{3}-[A-Z]{2}"/>
        </xsd:restriction>
       </xsd:simpleType>
      </xsd:schema>
    2. 使用 Xsd.exe 工具生成类文件。 例如,以下命令行代码生成 C# 类:
      xsd /classes /language:C# PO.xsd
      Xsd.exe 工具在和上面给出的架构一起使用时为 Visual Basic .Net 生成以下类:
      Imports System.Xml.Serialization
      Namespace XmlSerializationHowTo    
          <System.Xml.Serialization.XmlRootAttribute("purchaseOrder", [Namespace]:="", IsNullable:=false)>  _
          Public Class PurchaseOrder
                      <System.Xml.Serialization.XmlElementAttribute(IsNullable:=false)>  _
              Public shipTo As USAddress
                   <System.Xml.Serialization.XmlElementAttribute(IsNullable:=false)>  _
              Public billTo As USAddress
              <System.Xml.Serialization.XmlElementAttribute(IsNullable:=false)>  _
              Public comment As String
              
              <System.Xml.Serialization.XmlArrayAttribute(IsNullable:=false),  _
               System.Xml.Serialization.XmlArrayItemAttribute("item", IsNullable:=false)>  _
              Public items() As ItemsItem
              <System.Xml.Serialization.XmlAttributeAttribute(DataType:="date")>  _
              Public orderDate As Date
              
              <System.Xml.Serialization.XmlIgnoreAttribute()>  _
              Public orderDateSpecified As Boolean
      End Class
      
          Public Class USAddress
              <System.Xml.Serialization.XmlElementAttribute(IsNullable:=false)>  _
              Public name As String
              <System.Xml.Serialization.XmlElementAttribute(IsNullable:=false)>  _
              Public street As String  
              <System.Xml.Serialization.XmlElementAttribute(IsNullable:=false)>  _
              Public city As String
              <System.Xml.Serialization.XmlElementAttribute(IsNullable:=false)>  _
              Public state As String
              
              Public zip As Decimal
              <System.Xml.Serialization.XmlAttributeAttribute(DataType:="NMTOKEN")>  _
              Public country As String
      End Class
          
          <System.Xml.Serialization.XmlTypeAttribute([Namespace]:="")>  _
          Public Class ItemsItem
              <System.Xml.Serialization.XmlElementAttribute(IsNullable:=false)>  _
              Public productName As String
              <System.Xml.Serialization.XmlElementAttribute(DataType:="positiveInteger", IsNullable:=false)>  _
              Public quantity As String
              
              Public USPrice As Decimal
              <System.Xml.Serialization.XmlElementAttribute(IsNullable:=false)>  _
              Public comment As String
              
              <System.Xml.Serialization.XmlElementAttribute(DataType:="date", IsNullable:=false)>  _
              Public shipDate As Date
              
              <System.Xml.Serialization.XmlIgnoreAttribute()>  _
              Public shipDateSpecified As Boolean
              
              <System.Xml.Serialization.XmlAttributeAttribute()>  _
              Public partNum As String
      End Class
      End Namespace
      请注意,Xsd.exe 并不使用类插入名称空间名称。 用户必须根据应用程序设计手动完成此操作。 在此示例中,XmlSerializationHowTo 名称空间用于包装 Xsd.exe 生成的类。
  2. 若要使用 Xsd.exe 工具创建可序列化的类,请按照下列步骤操作: 在创建可序列化的类之后,打开 Visual Studio .NET 以创建新的序列化项目。
  3. 若要使用 Xsd.exe 工具创建可序列化的类,请按照下列步骤操作: 新建 C# 或 Visual Basic .NET 控制台应用程序。
  4. 若要使用 Xsd.exe 工具创建可序列化的类,请按照下列步骤操作: 将 Xsd.exe 生成的类文件插到您的项目中。 为此,在解决方案资源管理器窗口中右键单击您的项目,单击添加,选择添加现有项,然后浏览以前生成的类文件。
  5. 若要使用 Xsd.exe 工具创建可序列化的类,请按照下列步骤操作: 确保该项目包含对上述步骤中创建的 System.Xml XmlSerializationHowTo 名称空间的引用。 在 Xml 名称空间上使用 IMPORTS 语句,这样,以后就不需要在代码中的这些名称空间限定 XmlSerializer 声明了。IMPORTS 语句必须位于任何其他声明之前。 Visual Basic .NET 代码
    Imports System.Xml.Serialization
    Imports System.IO
    Imports XmlSerializationHowTo
    C# 代码
    using System.Xml.Serialization;
    using System.IO;
    using XmlSerializationHowTo;
  6. 若要使用 Xsd.exe 工具创建可序列化的类,请按照下列步骤操作: 创建 XmlSerializer 类的一个实例,并传递要反序列化的对象的类型。 该示例使用以前定义的 PurchaseOrder 类型。 Visual Basic .NET 代码
    Dim serializer As XmlSerializer = New XmlSerializer(GetType(PurchaseOrder))
    C# 代码
    XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
  7. 若要使用 Xsd.exe 工具创建可序列化的类,请按照下列步骤操作: 若要读取该文件,请调用 Deserialize 方法,并传递到 StreamTextReader XmlReader 类中。 此时,就会返回一个订单。 在该示例中,使用以下代码: Visual Basic .NET 代码
    Dim reader As TextReader = New StreamReader("po.xml")
    Dim po As PurchaseOrder = CType(serializer.Deserialize(reader), PurchaseOrder)
    reader.Close()
    C# 代码
    TextReader reader = new StreamReader("po.xml");
    PurchaseOrder po = (PurchaseOrder)serializer.Deserialize(reader);
    reader.Close();
    Po.xml 包含与订单关联的数据,这些订单遵循以前定义的 XSD 架构。 下面是该文件的内容:
    <?xml version='1.0' encoding='utf-16'?>
    <purchaseOrder orderDate="1999-10-20">
        <shipTo country="US">
            <name>Alice Smith</name>
            <street>123 Maple Street</street>
            <city>Mill Valley</city>
    <state>CA</state>
            <zip>90952</zip>
        </shipTo>
        <billTo country="US">
            <name>Robert Smith</name>
            <street>8 Oak Avenue</street>
            <city>Old Town</city>
    <state>PA</state>
            <zip>95819</zip>
        </billTo>
        <comment>Hurry, my lawn is going wild!</comment>
        <items>
            <item partNum="872-AA">
                <productName>Lawnmower</productName>
                <quantity>1</quantity>
                <price>148.95</price>
                <comment>Confirm this is electric</comment>
            </item>
            <item partNum="926-AA">
                <productName>Baby Monitor</productName>
                <quantity>1</quantity>
                <price>39.98</price>
                <shipDate>1999-05-21</shipDate>
            </item>
        </items>
    </purchaseOrder>
  8. 若要使用 Xsd.exe 工具创建可序列化的类,请按照下列步骤操作: 按照操作任何对象的一般方式操作 PurchaseOrder 对象(通过 PO 变量)。
  9. 若要使用 Xsd.exe 工具创建可序列化的类,请按照下列步骤操作: 将修改后的数据保存到一个新的 XML 文件中。 若要写入该文件,请调用 Serialize 方法,并传递到 StreamTextReader XmlReader 类以及订单的实例中: Visual Basic .NET 代码
    Dim writer As TextWriter = New StreamWriter("po2.xml")
    serializer.Serialize(writer, po)
    writer.Close()
    C# 代码
    TextWriter writer = new StreamWriter("po2.xml");
    serializer.Serialize(writer, po);
    writer.Close();
  10. 若要使用 Xsd.exe 工具创建可序列化的类,请按照下列步骤操作: 保存并关闭项目。

参考

有关 XmlSerializerStreamWriter StreamReader 类的更多信息,请参见 .NET 框架类库文档。

有关序列化的更多信息,请参见 .NET 框架开发人员指南文档。

有关如何使用 XML 架构定义工具 (XSD.exe) 的更多信息,请参见 .NET 框架开发人员指南文档或 .NET 框架工具文档。

返回页首

这篇文章中的信息适用于:

  • Microsoft .NET Development Platform (NDP) Beta 2
最近更新:2001-11-2 (1.0)
关键字kbhowto kbHOWTOmaster kbXML tslic_tslic KB301223 kbAudDeveloper
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值