序列化确实是将对象的状态转换为可以存储或传输的格式的过程。在 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中文网其他相关文章!