溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

XML串行化的示例分析

發(fā)布時(shí)間:2021-07-27 11:04:13 來(lái)源:億速云 閱讀:107 作者:小新 欄目:編程語(yǔ)言

小編給大家分享一下XML串行化的示例分析,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!



    XML 串行化(XML serialization)只串行public字段(fields)和性質(zhì)(property).XML 串行化不會(huì)包含類(lèi)型信息.因?yàn)閄ML有極好的機(jī)制用來(lái)描述數(shù)據(jù)和分級(jí)關(guān)系,所以它很適合保存對(duì)象的串行化信息。

     注:XML 串行化不會(huì)轉(zhuǎn)化方法(methods), 索引器(indexers), private fields, 或者只讀性質(zhì)(properties)(除了只讀的collections). 要串行化包括public和private 所有的字段(fields)和性質(zhì)性(property),用BinaryFormatter來(lái)代替XML 串行化.

      下面是使用XML 串行化(XML serialization)的示例:

串行化DataSet

private void SerializeDataSet(string filename){
    XmlSerializer ser = new XmlSerializer(typeof(DataSet));
        
    // Creates a DataSet; adds a table, column, and ten rows.
    DataSet ds = new DataSet("myDataSet");
    DataTable t = new DataTable("table1");
    DataColumn c = new DataColumn("thing");
    t.Columns.Add(c);
    ds.Tables.Add(t);
    DataRow r;
    for(int i = 0; i<10;i++){
        r = t.NewRow();
        r[0] = "Thing " + i;
        t.Rows.Add(r);
    }
    TextWriter writer = new StreamWriter(filename);
    ser.Serialize(writer, ds);
    writer.Close();
}

-----------------------------------
串行化XmlElement和XmlNode

private void SerializeElement(string filename){
    XmlSerializer ser = new XmlSerializer(typeof(XmlElement));
    XmlElement myElement= 
    new XmlDocument().CreateElement("MyElement", "ns");
    myElement.InnerText = "Hello World";
    TextWriter writer = new StreamWriter(filename);
    ser.Serialize(writer, myElement);
    writer.Close();
}

private void SerializeNode(string filename){
    XmlSerializer ser = new XmlSerializer(typeof(XmlNode));
    XmlNode myNode= new XmlDocument().
    CreateNode(XmlNodeType.Element, "MyNode", "ns");
    myNode.InnerText = "Hello Node";
    TextWriter writer = new StreamWriter(filename);
    ser.Serialize(writer, myNode);
    writer.Close();
}

----------------------------------------------

串行化包含返回復(fù)雜對(duì)象(Object)的類(lèi)(Class)

   如果一個(gè)字段(fields)和性質(zhì)(property)返回一個(gè)復(fù)雜對(duì)象(如:array 或者一個(gè)類(lèi)的實(shí)例(class instance)).XmlSerializer把它轉(zhuǎn)化為嵌套在主XML文檔的元素.如下,第一個(gè)類(lèi)返回第二個(gè)類(lèi)的一個(gè)實(shí)例.

public class PurchaseOrder
{
    public Address MyAddress;
}
public class Address
{
    public string FirstName;
}

串行化輸出的XML類(lèi)似下面

<PurchaseOrder>
    <Address>
        <FirstName>George</FirstName>
    </Address>
</PurchaseOrder>

--------------------------------------------------
串行化對(duì)象(object)隊(duì)列

你可以串行化返回對(duì)象隊(duì)列的字段(field)

public class PurchaseOrder
{
    public Item [] ItemsOrders
}
public class Item
{
    public string ItemID
    public decimal ItemPrice
}

串行化輸出的XML類(lèi)似下面

<PurchaseOrder xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd="http://www.w3.org/20001/XMLSchema">
    <Items>
        <Item>
            <ItemID>aaa111</ItemID>
            <ItemPrice>34.22</ItemPrice>
        <Item>
        <Item>
            <ItemID>bbb222</ItemID>
            <ItemPrice>2.89</ItemPrice>
        <Item>
    </Items>
</PurchaseOrder>

----------------------------------------------------------------------
串行化實(shí)現(xiàn)ICollection接口的類(lèi)

你可以同時(shí)實(shí)現(xiàn)ICollection接口來(lái)創(chuàng)建集合類(lèi),并使用XmlSerializer來(lái)串行化類(lèi)的實(shí)例.注意當(dāng)一個(gè)類(lèi)實(shí)現(xiàn)ICollection接口時(shí),只有包含在類(lèi)里的集合會(huì)被串行化,其他任何添加到類(lèi)的字段(fields)和性質(zhì)(property)都不會(huì)被串行化.被串行化的類(lèi)必須包含Add方法(method)和Item性質(zhì)(property)(C#的索引器(indexer)).

using System;
using System.IO;
using System.Collections;
using System.Xml.Serialization;
public class Test{
    static void Main(){
        Test t = new Test();
        t.SerializeCollection("coll.xml");
    }
    private void SerializeCollection(string filename){
        Employees Emps = new Employees();
        // Note that only the collection is serialized--not the 
        // CollectionName or any other public property of the class.
        Emps.CollectionName = "Employees";
        Employee John100 = new Employee("John", "100xxx");
        Emps.Add(John100);
        XmlSerializer x = new XmlSerializer(typeof(Employees));
        TextWriter writer = new StreamWriter(filename);
        x.Serialize(writer, Emps);
    }
}
public class Employees:ICollection{
    public string CollectionName;
    private ArrayList empArray = new ArrayList();
    //所要求要求的Item性質(zhì)(property)(C#的索引器(indexer))
    public Employee this[int index]{
        get{return (Employee) empArray[index];}
    }
    
    public void CopyTo(Array a, int index){
        empArray.CopyTo(a, index);
    }
    public int Count{
        get{return empArray.Count;}
    }
    public object SyncRoot{
        get{return this;}
    }
    public bool IsSynchronized{
        get{return false;}
    }
    public IEnumerator GetEnumerator(){
        return empArray.GetEnumerator();
    }
    //所要求的Add方法,它只能有一個(gè)參數(shù),并且此參數(shù)的類(lèi)型必須為Item性質(zhì)(property)(C#的索引器(indexer))所返回的類(lèi)型
    public void Add(Employee newEmployee){
        empArray.Add(newEmployee);
    }
}
public class Employee{
    public string EmpName;
    public string EmpID;
    public Employee(){}
    public Employee(string empName, string empID){
        EmpName = empName;
        EmpID = empID;
    }
}


Note:當(dāng)我們?cè)O(shè)計(jì)和使用被串行化的強(qiáng)類(lèi)型(strongly-typed)集合類(lèi)時(shí),需要注意:

   由于規(guī)則的限制,你的類(lèi)將被串行化為你的類(lèi)所包含集合(collection )類(lèi)型的集合(array),就是說(shuō)如果你添加了額外的性質(zhì)(properties),它們?cè)诖谢瘯r(shí)將不會(huì)被包含進(jìn)來(lái). 例如:

XML串行化的示例分析



   這里CustomerAccounts將會(huì)被串行化,但是會(huì)被串行化成一個(gè)Account對(duì)象的集合Name, Address等字段都不會(huì)被串行化.一個(gè)顯而易見(jiàn)的解決辦法像如下所示:

XML串行化的示例分析

這里時(shí)MSDN對(duì)它的介紹:

XmlSerializer can process classes that implement IEnumerable or ICollection differently if they meet certain requirements. A class that implements IEnumerable must implement a public Add method that takes a single parameter. The Add method's parameter must be consistent (polymorphic) with the type returned from the IEnumerator.Current property returned from the GetEnumerator method. A class that implements ICollection in addition to IEnumerable (such as CollectionBase) must have a public Item indexed property (an indexer in C#) that takes an integer, and it must have a public Count property of type integer. The parameter passed to the Add method must be the same type as that returned from the Item property, or one of that type's bases. For classes implementing ICollection, values to be serialized will be retrieved from the indexed Item property rather than by calling GetEnumerator. Also note that public fields and properties will not be serialized, with the exception of public fields that return another collection class (one that implements ICollection).

 使用XML串行化屬性(Attributes)(如:XmlArray,XmlArrayItem)來(lái)串行化集合類(lèi)!

串行化包含數(shù)組(Arrays)的數(shù)據(jù)

using System;
using System.Collections;
using System.Xml.Serialization;
 /// <summary>
 /// Summary description for Cars.
 /// </summary>
    [XmlRoot("carsCollection")]
    public class CarsArray {
        private Car[] _CarsList = null;

        public CarsArray() {}    
    
        public CarsArray(int size) {
            _CarsList = new Car[size];
        }

        [XmlArray("carsArray")]
        [XmlArrayItem("car")]
        public Car[] CarsCollection {
            get {
                return _CarsList;
            }
            set {
                _CarsList = value;
            }
        }

        public Car this[int index] {
            get {
                if (index <= _CarsList.GetUpperBound(0) || index > -1)
                    return (Car)_CarsList[index];
                else
                    throw new IndexOutOfRangeException("Invalid index value passed.");
            }
            set {
                if (index <= _CarsList.GetUpperBound(0) || index > -1)
                    _CarsList[index] = value;
                else
                    throw new IndexOutOfRangeException("Invalid index value passed.");

            }
        }

    }

結(jié)果為:

<?xml version="1.0" encoding="utf-16"?>
<carsCollection xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <carsArray>
    <car>
      <license>1234</license>
      <color>Black</color>
    </car>
    <car>
      <license>4321</license>
      <color>Blue</color>
    </car>
  </carsArray>
</carsCollection>
  • 串行化ArrayLists

  • using System;
    using System.Collections;
    using System.Xml.Serialization;
    
        /// <summary>
        /// Summary description for Cars.
        /// </summary>
        [XmlRoot("carsCollection")]
        public class CarsArrayList {
            private ArrayList _CarsList = new ArrayList();
    
            public CarsArrayList() {}        
    
            [XmlArray("carsArrayList")]
            [XmlArrayItem("car",typeof(Car))]
            public ArrayList CarsCollection {
                get {
                    return _CarsList;
                }
                set {
                    _CarsList = value;
                }
            }
    
            public Car this[int index] {
                get {
                    return (Car)_CarsList[index];
                }
                set {
                    if (index > _CarsList.Count-1)
                        _CarsList.Add(value);
                    else
                        _CarsList[index] = value;
                }
            }
    
        }



結(jié)果為:

<?xml version="1.0" encoding="utf-16"?>
<carsCollection xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <carsArrayList>
    <car>
      <license>1234</license>
      <color>Black</color>
    </car>
    <car>
      <license>4321</license>
      <color>Blue</color>
    </car>
  </carsArrayList>
</carsCollection>

------------------------------------------------------------------

購(gòu)買(mǎi)訂單示例

   例子很簡(jiǎn)單,也很完整,它使用CreatePO來(lái)創(chuàng)建 PurchaseOrder, Address,和 OrderedItem類(lèi),并串行化它們.ReadPo實(shí)現(xiàn)反串行化.

   可以將附加的特性用于類(lèi)和屬性.你必須引用System.Xml.Serialization名字空間來(lái)用這些特性.

特性用途
[XmlIgnore]當(dāng)公有的屬性或字段不包括在串行化的XML結(jié)構(gòu)中時(shí)。
[XmlRoot]用來(lái)識(shí)別作為XML文件根元素的類(lèi)或結(jié)構(gòu)。你可以用它來(lái)把一個(gè)元素名設(shè)置為根元素。
[XmlElement]當(dāng)公有的屬性或字段可以作為一個(gè)元素被串行化到XML結(jié)構(gòu)中時(shí)。
[XmlAttribute]當(dāng)公有的屬性或字段可以作為一個(gè)特性被串行化到XML結(jié)構(gòu)中時(shí)。
[XmlArray]當(dāng)公有的屬性或字段可以作為一個(gè)元素?cái)?shù)組被串行化到XML結(jié)構(gòu)中時(shí)。當(dāng)一組對(duì)象用在一個(gè)類(lèi)中時(shí),這個(gè)特性很有用。
[XmlArrayItem]用來(lái)識(shí)別可以放到一個(gè)串行化數(shù)組中的類(lèi)型。



   再次提醒大家注意,只能串行化公共(public)類(lèi)和公共(public)字段(fields)和性質(zhì)(property).

using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
// The XmlRootAttribute allows you to set an alternate name 
// (PurchaseOrder) for the XML element and its 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");
    }
    private void CreatePO(string filename)
    {
        // Creates an instance of the XmlSerializer class;
        // specifies the type of object to serialize.
        XmlSerializer serializer = 
        new XmlSerializer(typeof(PurchaseOrder));
        TextWriter writer = new StreamWriter(filename);
        PurchaseOrder po=new PurchaseOrder();
         
        // Creates 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";
        // Sets ShipTo and BillTo to the same addressee.
        po.ShipTo = billAddress;
        po.OrderDate = System.DateTime.Now.ToLongDateString();
    
        // Creates an OrderedItem.
        OrderedItem i1 = new OrderedItem();
        i1.ItemName = "Widget S";
        i1.Description = "Small widget";
        i1.UnitPrice = (decimal) 5.23;
        i1.Quantity = 3;
        i1.Calculate();
    
        // Inserts 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; 
        // Serializes the purchase order, and closes the TextWriter.
        serializer.Serialize(writer, po);
        writer.Close();
    }
    
    protected void ReadPO(string filename)
    {
        // Creates an instance of the XmlSerializer class;
        // specifies 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, handles them with the 
        // UnknownNode and UnknownAttribute events.
        //在并行的xml當(dāng)中可能存在意外的xml節(jié)點(diǎn),如果不處理這些意外的xml 的節(jié)
        //點(diǎn),XmlSerializer將忽略這些意外的節(jié)點(diǎn),如果要處理這些意外節(jié)點(diǎn),可以使用
        //XmlSerializer的一下事件進(jìn)行處理:UnknownNode,UnknownElement  ,
        //UnknownAttribute ,UnreferencedObject
        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);
        // Declares an object variable of the type to be deserialized.
        PurchaseOrder po;
        // Uses the Deserialize method to restore the object's state with
        // data from the XML document. */
        po = (PurchaseOrder) serializer.Deserialize(fs);
        // Reads the order date.
        Console.WriteLine ("OrderDate: " + po.OrderDate);
    
        // Reads the shipping address.
        Address shipTo = po.ShipTo;
        ReadAddress(shipTo, "Ship To:");
        // Reads 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);
        }
        // Reads the subtotal, shipping cost, and total cost.
        Console.WriteLine(
        "\n\t\t\t\t\t Subtotal\t" + po.SubTotal + 
        "\n\t\t\t\t\t Shipping\t" + po.ShipCost + 
        "\n\t\t\t\t\t Total\t\t" + po.TotalCost
        );
    }
    
    protected void ReadAddress(Address a, string label)
    {
        // Reads the fields of the Address.
        Console.WriteLine(label);
        Console.Write("\t"+
        a.Name +"\n\t" +
        a.Line1 +"\n\t" +
        a.City +"\t" +
        a.State +"\n\t" +
        a.Zip +"\n");
    }
    protected void serializer_UnknownNode
    (object sender, XmlNodeEventArgs e)
    {
        Console.WriteLine("Unknown Node:" +   e.Name + "\t" + e.Text);
    }
    protected void serializer_UnknownAttribute
    (object sender, XmlAttributeEventArgs e)
    {
        System.Xml.XmlAttribute attr = e.Attr;
        Console.WriteLine("Unknown attribute " + 
        attr.Name + "='" + attr.Value + "'");
    }
}

xml輸出如下:

<?xml version="1.0" encoding="utf-8"?>
<PurchaseOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.cpandl.com">
    <ShipTo Name="Teresa Atkinson">
        <Line1>1 Main St.</Line1>
        <City>AnyTown</City>
        <State>WA</State>
        <Zip>00000</Zip>
    </ShipTo>
    <OrderDate>Wednesday, June 27, 2001</OrderDate>
    <Items>
        <OrderedItem>
            <ItemName>Widget S</ItemName>
            <Description>Small widget</Description>
            <UnitPrice>5.23</UnitPrice>
            <Quantity>3</Quantity>
            <LineTotal>15.69</LineTotal>
        </OrderedItem>
    </Items>
    <SubTotal>15.69</SubTotal>
    <ShipCost>12.51</ShipCost>
    <TotalCost>28.2</TotalCost>
</PurchaseOrder>

以上是“XML串行化的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

xml
AI