如何将对象读写到 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 工具创建可序列化的类,请按照下列步骤操作: 保存并关闭项目。

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值