序列化確實是將物件的狀態轉換為可以儲存或傳輸的格式的過程。在 C# 中,可以使用 XmlSerializer 類別將物件序列化為 XML 格式。它可以將 C# 物件轉換為 XML 表示形式,從而可以更輕鬆地透過 Internet 進行傳輸並簡化對檔案的寫入。
文法:
XmlSerializer variable_name = new XmlSerializer();
其中variable_name代表XmlSerializer類別的實例。
在 C# 中將物件轉換為 XML 的步驟如下:
讓我們討論 XML 物件的範例。
C# 程式將給定物件轉換為 XML 格式並將內容寫入儲存在指定位置的 XML 文件,然後顯示文件內容:
代碼:
using System.Xml.Serialization; using System.IO; //a class called Country is defined within which the two strings are defined public class Country { public string name = "India"; public string capital = "New Delhi"; } //main method is called static void Main(string[] args) { //an instance of the class country is created Country c = new Country(); //an instance of the XmlSerializer class is created XmlSerializer inst = new XmlSerializer(typeof(Country)); //an instance of the TextWriter class is created to write the converted XML string to the file TextWriter writer = new StreamWriter(@ "C:\Users\admin\Desktop\check.xml"); inst.Serialize(writer, c); writer.Close(); }
上述程式的輸出如下圖:
最後,程式以 XML 格式顯示檔案內容作為螢幕上的輸出,如提供的快照所示。
C# 程式將給定物件轉換為 XML 格式並將內容寫入儲存在指定位置的 XML 文件,然後顯示文件內容:
代碼:
using System.Xml.Serialization; using System.IO; //a class called Learning is defined within which the two strings are defined public class Learning { public string organization = "EDUCBA"; public string topic = "C#"; } //main method is called static void Main(string[] args) { //an instance of the class Learning is created Country c = new Learning(); //an instance of the XmlSerializer class is created XmlSerializer inst = new XmlSerializer(typeof(Learning)); //an instance of the TextWriter class is created to write the converted XML string to the file TextWriter writer = new StreamWriter(@ "C:\Users\admin\Desktop\check.xml"); inst.Serialize(writer, c); writer.Close(); }
上述程式的輸出如下圖:
在給定的程式中,名為「Learning」的類別定義了兩個字串「organization」和「topic」。然後,程式將文件的 XML 格式內容顯示為螢幕上的輸出,如提供的快照所示。
C# 程序,將給定的 C# 物件轉換為 XML 格式,並將內容寫入儲存在指定位置的 XML 文件,然後顯示該文件的內容:
代碼:
using System.Xml.Serialization; using System.IO; //a class called University is defined within which the two strings are defined public class University { public string name = "VTU"; public string stream = "BE"; } //main method is called static void Main(string[] args) { //an instance of the class University is created Country c = new University(); //an instance of the XmlSerializer class is created XmlSerializer inst = new XmlSerializer(typeof(University)); //an instance of the TextWriter class is created to write the converted XML string to the file TextWriter writer = new StreamWriter(@ "C:\Users\admin\Desktop\check.xml"); inst.Serialize(writer, c); writer.Close(); }
上述程式的輸出如下圖:
程式定義了一個名為University的類,它定義了兩個字串:name和stream。然後它會呼叫 main 方法,該方法會建立 XmlSerializer 類別的實例以將 University 物件序列化為 XML 格式。然後,它會建立 TextWriter 類別的實例,以將轉換後的 XML 字串寫入檔案中的指定位置。最後,它以 XML 格式顯示檔案內容,作為螢幕上的輸出。
在本文中,我們透過程式設計範例及其輸出了解了使用 XmlSerializer() 函數將物件轉換為 XML 的概念、定義、語法和步驟。
以上是C# 物件到 XML的詳細內容。更多資訊請關注PHP中文網其他相關文章!