XML串行化的範例程式碼分享
串列化是將 Object轉換為可以用來傳送的一種形態,例如:你可以串列化一個Object並在Client端和Server端使用Http透過Internet傳遞.在另一邊使用反串行化把流轉換為Object.
XML串列化(XML serialization)只串列public字段(fields)和性質(property).XML 串列化不會包含類型資訊.因為XML有極佳的機制用來描述資料和分級關係,所以它很適合保存物件的串列化資訊。
fields, 或唯讀性質(properties)(除了唯讀的collections). 要串列化包括public和private 所有的字段(fields)和性質性(property),用
BinaryFormatter來取代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();
}
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();
}
序列化包含傳回複雜物件(Object)的類別(
Class
) 如果一個字段(fields)和性質(property)傳回一個複雜物件(如:array
或一個類別的實例(class instance)).XmlSerializer轉化它為嵌套在主XML文檔的元素。如下,第一個類別傳回第二個類別的一個實例.public class PurchaseOrder
{
public Address MyAddress;
}
public class Address
{
public string FirstName;
}
<PurchaseOrder> <Address> <FirstName>George</FirstName> </Address> </PurchaseOrder>
---------- ----------------------------------------
你可以串列化回傳物件佇列的欄位(field)
public class PurchaseOrder { public Item [] ItemsOrders } public class Item { public string ItemID public decimal ItemPrice }
序列化輸出的XML類似下方
<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>
---------------------------------------------- ------------------------
介面
的類別#你可以同時實作ICollection
介面來建立集合類別,並使用
XmlSerializer來串列化類別的實例。注意當一個類別實作ICollection介面時,只有包含在類別裡的集合會被串行化,其他任何添加到類別的字段(fields)和性質(property)都不會被串行化.被串行化的類別必須包含Add 方法(method)和Item性質(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性质(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方法,它只能有一个参数,并且此参数的类型必须为Item性质(property)(C#的索引器(indexer))所返回的类型
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:當我們設計和使用被串列化的強型別(strongly-typed)集合類別時,需要注意:
由於規則的限制,你的類別將被串列化為你的類別所包含集合(collection )類型的集合(array),就是說如果你加入了額外的性質(properties),它們在串列化時將不會被包含進來. 例如:
這裡
#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'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串行化的範例程式碼分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

XML檔可以用PPT開啟嗎? XML,即可擴展標記語言(ExtensibleMarkupLanguage),是一種廣泛應用於資料交換和資料儲存的通用標記語言。與HTML相比,XML更加靈活,能夠定義自己的標籤和資料結構,使得資料的儲存和交換更加方便和統一。而PPT,即PowerPoint,是微軟公司開發的一種用於創建簡報的軟體。它提供了圖文並茂的方

使用Python實現XML資料的合併和去重XML(eXtensibleMarkupLanguage)是一種用於儲存和傳輸資料的標記語言。在處理XML資料時,有時候我們需要將多個XML檔案合併成一個,或移除重複的資料。本文將介紹如何使用Python實現XML資料的合併和去重的方法,並給出對應的程式碼範例。一、XML資料合併當我們有多個XML文件,需要將其合

Python中的XML資料轉換為CSV格式XML(ExtensibleMarkupLanguage)是一種可擴充標記語言,常用於資料的儲存與傳輸。而CSV(CommaSeparatedValues)則是一種以逗號分隔的文字檔案格式,常用於資料的匯入和匯出。在處理資料時,有時需要將XML資料轉換為CSV格式以便於分析和處理。 Python作為一種功能強大

使用Python實現XML資料的篩選和排序引言:XML是一種常用的資料交換格式,它以標籤和屬性的形式儲存資料。在處理XML資料時,我們經常需要對資料進行篩選和排序。 Python提供了許多有用的工具和函式庫來處理XML數據,本文將介紹如何使用Python實現XML資料的篩選和排序。讀取XML檔案在開始之前,我們需要先讀取XML檔案。 Python有許多XML處理函式庫,

使用PHP將XML資料匯入資料庫引言:在開發中,我們經常需要將外部資料匯入到資料庫中進行進一步的處理和分析。而XML作為一種常用的資料交換格式,也常被用來儲存和傳輸結構化資料。本文將介紹如何使用PHP將XML資料匯入資料庫。步驟一:解析XML文件首先,我們需要解析XML文件,擷取所需的資料。 PHP提供了幾種解析XML的方式,其中最常用的是使用Simple

Python實作XML與JSON之間的轉換導語:在日常的開發過程中,我們常常需要將資料在不同的格式之間轉換。 XML和JSON是常見的資料交換格式,在Python中,我們可以使用各種函式庫來實作XML和JSON之間的相互轉換。本文將介紹幾種常用的方法,並附帶程式碼範例。一、XML轉JSON在Python中,我們可以使用xml.etree.ElementTree模

使用Python處理XML中的錯誤和異常XML是一種常用的資料格式,用於儲存和表示結構化的資料。當我們使用Python處理XML時,有時可能會遇到一些錯誤和異常。在本篇文章中,我將介紹如何使用Python來處理XML中的錯誤和異常,並提供一些範例程式碼供參考。使用try-except語句捕捉XML解析錯誤當我們使用Python解析XML時,有時候可能會遇到一些

Python解析XML中的特殊字元和轉義序列XML(eXtensibleMarkupLanguage)是一種常用的資料交換格式,用於在不同系統之間傳輸和儲存資料。在處理XML檔案時,經常會遇到包含特殊字元和轉義序列的情況,這可能會導致解析錯誤或誤解資料。因此,在使用Python解析XML檔案時,我們需要了解如何處理這些特殊字元和轉義序列。一、特殊字元和
