ホームページ バックエンド開発 XML/RSS チュートリアル XML シリアル化サンプル コードの共有

XML シリアル化サンプル コードの共有

Mar 22, 2017 pm 05:16 PM

シリアル化とは、オブジェクト を送信に使用できる形式に変換することです。例: オブジェクトをシリアル化できます。一方、Property.XML シリアル化には、データを記述するための優れたメカニズムがあるため、ストリームをオブジェクトに変換するために使用されます。 XML シリアル化では、メソッド、インデクサー、
プライベート
フィールド、または読み取り専用プロパティ (読み取り専用コレクションを除く) は変換されません。シリアル化には、すべてのパブリックフィールド(フィールド)とプロパティが含まれます。XMLシリアル化を置き換えるために、bimaryFormatterを使用します。 --------XmlElement と XmlNode をシリアル化する

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();
}
ログイン後にコピー

---- ------------------------ ----------------
シリアル化には戻り値が含まれます 複合オブジェクト(Object)のクラス(Class)


フィールド(fields)とプロパティ(property)の場合複雑なオブジェクト (
array やクラス インスタンスなど) を返します。 次のように、最初のクラスは 2 番目のクラスのインスタンスを返します。次のようなものです
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();
}
ログイン後にコピー

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


シリアル化されたオブジェクト)Queue
オブジェクトキューを返すフィールドをシリアル化できます

public class PurchaseOrder
{
    public Address MyAddress;
}
public class Address
{
    public string FirstName;
}
ログイン後にコピー

シリアル化された出力XMLは次のようになります
<PurchaseOrder>
    <Address>
        <FirstName>George</FirstName>
    </Address>
</PurchaseOrder>
ログイン後にコピー
------ ---------- -------------------------------------- ---------- ----
ICollection
インターフェースを実装するクラスをシリアル化する

コレクションクラスを作成すると同時に

ICollection

インターフェースを実装し、
XmlSerializerを使用することができますクラスが

ICollection

Interface を実装する場合、クラスに含まれるコレクションのみがシリアル化され、クラスに追加された他のフィールドやプロパティはシリアル化されないことに注意してください。
AddメソッドとItem
プロパティ(
C#
indexer).

public class PurchaseOrder
{
    public Item [] ItemsOrders
}
public class Item
{
    public string ItemID
    public decimal ItemPrice
}
ログイン後にコピー

注: 厳密に型指定されたシリアル化) コレクション クラスを設計して使用する場合は、次の点に注意する必要があります。


ルールの制限により、クラスはクラスに含まれるコレクション型の配列にシリアル化されます。つまり、追加のプロパティ (プロパティ) を追加した場合、それらはシリアル化時に含まれません。 例:

ここでCustomerAccountsはシリアル化されますが、AccountオブジェクトのコレクションName、Address
および他のフィールドはシリアル化されません:





这里时MSDN对它的介绍:

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)来串行化集合类!

串行化包含数组(Arrays)的数据

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.");

            }
        }

    }
ログイン後にコピー

结果为:

<?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;
                }
            }
    
        }
    ログイン後にコピー



结果为:

<?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>
ログイン後にコピー

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

购买订单示例

例子很简单,也很完整,它使用CreatePO来创建 PurchaseOrder, Address,和 OrderedItem类,并串行化它们.ReadPo实现反串行化.

可以将附加的特性用于类和属性.你必须引用System.Xml.Serialization名字空间来用这些特性.

特性用途
[XmlIgnore]当公有的属性或字段不包括在串行化的XML结构中时。
[XmlRoot]用来识别作为XML文件根元素的类或结构。你可以用它来把一个元素名设置为根元素。
[XmlElement]当公有的属性或字段可以作为一个元素被串行化到XML结构中时。
[XmlAttribute]当公有的属性或字段可以作为一个特性被串行化到XML结构中时。
[XmlArray]当公有的属性或字段可以作为一个元素数组被串行化到XML结构中时。当一组对象用在一个类中时,这个特性很有用。
[XmlArrayItem]用来识别可以放到一个串行化数组中的类型。



再次提醒大家注意,只能串行化公共(public)类和公共(public)字段(fields)和性质(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当中可能存在意外的xml节点,如果不处理这些意外的xml 的节
        //点,XmlSerializer将忽略这些意外的节点,如果要处理这些意外节点,可以使用
        //XmlSerializer的一下事件进行处理: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&#39;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 + "=&#39;" + attr.Value + "&#39;");
    }
}
ログイン後にコピー

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 シリアル化サンプル コードの共有の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

PowerPoint を使用して XML ファイルを開くことはできますか? PowerPoint を使用して XML ファイルを開くことはできますか? Feb 19, 2024 pm 09:06 PM

XML ファイルは PPT で開くことができますか? XML、Extensible Markup Language (Extensible Markup Language) は、データ交換とデータ ストレージで広く使用されている汎用マークアップ言語です。 HTML と比較して、XML はより柔軟であり、独自のタグとデータ構造を定義できるため、データの保存と交換がより便利で統一されます。 PPT (PowerPoint) は、プレゼンテーションを作成するために Microsoft によって開発されたソフトウェアです。包括的な方法を提供します。

Python を使用した XML データのマージと重複排除 Python を使用した XML データのマージと重複排除 Aug 07, 2023 am 11:33 AM

Python を使用した XML データのマージと重複排除 XML (eXtensibleMarkupLanguage) は、データの保存と送信に使用されるマークアップ言語です。 XML データを処理するとき、複数の XML ファイルを 1 つにマージしたり、重複データを削除したりする必要がある場合があります。この記事では、Python を使用して XML データのマージと重複排除を実装する方法と、対応するコード例を紹介します。 1. XML データのマージ 複数の XML ファイルがある場合、それらをマージする必要があります。

Python で XML データを CSV 形式に変換する Python で XML データを CSV 形式に変換する Aug 11, 2023 pm 07:41 PM

Python の XML データを CSV 形式に変換する XML (ExtensibleMarkupLanguage) は、データの保存と送信に一般的に使用される拡張可能なマークアップ言語です。 CSV (CommaSeparatedValues) は、データのインポートとエクスポートに一般的に使用されるカンマ区切りのテキスト ファイル形式です。データを処理するとき、分析や処理を容易にするために、XML データを CSV 形式に変換する必要がある場合があります。 Pythonは強力です

Python を使用した XML データのフィルタリングと並べ替え Python を使用した XML データのフィルタリングと並べ替え Aug 07, 2023 pm 04:17 PM

Python を使用した XML データのフィルタリングと並べ替えの実装 はじめに: XML は、データをタグと属性の形式で保存する、一般的に使用されるデータ交換形式です。 XML データを処理するとき、多くの場合、データのフィルタリングと並べ替えが必要になります。 Python には、XML データを処理するための便利なツールとライブラリが多数用意されています。この記事では、Python を使用して XML データをフィルタリングおよび並べ替える方法を紹介します。 XML ファイルの読み取り 始める前に、XML ファイルを読み取る必要があります。 Python には XML 処理ライブラリが多数ありますが、

PHP を使用して XML データをデータベースにインポートする PHP を使用して XML データをデータベースにインポートする Aug 07, 2023 am 09:58 AM

PHP を使用した XML データのデータベースへのインポート はじめに: 開発中、さらなる処理や分析のために外部データをデータベースにインポートする必要がよくあります。一般的に使用されるデータ交換形式として、XML は構造化データの保存と送信によく使用されます。この記事では、PHP を使用して XML データをデータベースにインポートする方法を紹介します。ステップ 1: XML ファイルを解析する まず、XML ファイルを解析し、必要なデータを抽出する必要があります。 PHP には XML を解析するためのいくつかの方法が用意されており、最も一般的に使用されるのは Simple を使用する方法です。

Python は XML と JSON 間の変換を実装します Python は XML と JSON 間の変換を実装します Aug 07, 2023 pm 07:10 PM

Python は XML と JSON 間の変換を実装します はじめに: 日常の開発プロセスでは、異なる形式間でデータを変換する必要があることがよくあります。 XML と JSON は一般的なデータ交換形式であり、Python ではさまざまなライブラリを使用して XML と JSON の間で変換できます。この記事では、一般的に使用されるいくつかの方法をコード例とともに紹介します。 1. Python で XML を JSON に変換するには、xml.etree.ElementTree モジュールを使用できます。

Python を使用した XML でのエラーと例外の処理 Python を使用した XML でのエラーと例外の処理 Aug 08, 2023 pm 12:25 PM

Python を使用した XML でのエラーと例外の処理 XML は、構造化データの保存と表現に使用される一般的に使用されるデータ形式です。 Python を使用して XML を処理すると、エラーや例外が発生することがあります。この記事では、Python を使用して XML のエラーと例外を処理する方法を紹介し、参考用のサンプル コードをいくつか示します。 Try-Except ステートメントを使用して XML 解析エラーを捕捉する Python を使用して XML を解析すると、時々、次のようなエラーが発生することがあります。

Python は XML 内の特殊文字とエスケープ シーケンスを解析します Python は XML 内の特殊文字とエスケープ シーケンスを解析します Aug 08, 2023 pm 12:46 PM

Python は XML 内の特殊文字とエスケープ シーケンスを解析します XML (eXtensibleMarkupLanguage) は、異なるシステム間でデータを転送および保存するために一般的に使用されるデータ交換形式です。 XML ファイルを処理する場合、特殊文字やエスケープ シーケンスが含まれる状況に遭遇することが多く、これにより解析エラーやデータの誤解が生じる可能性があります。したがって、Python を使用して XML ファイルを解析する場合は、これらの特殊文字とエスケープ シーケンスの処理方法を理解する必要があります。 1. 特殊文字と

See all articles