阅读量:0
在C#中,可以使用System.Xml.Serialization
命名空间中的XmlSerializer
类来实现对不同类型对象的XML序列化
- 首先,创建一个简单的类,例如
Person
:
public class Person { public string Name { get; set; } public int Age { get; set; } }
- 接下来,创建一个
XmlSerializer
实例,并使用Serialize
方法将Person
对象序列化为XML字符串:
using System; using System.IO; using System.Xml.Serialization; class Program { static void Main(string[] args) { Person person = new Person { Name = "John", Age = 30 }; XmlSerializer serializer = new XmlSerializer(typeof(Person)); using (StringWriter writer = new StringWriter()) { serializer.Serialize(writer, person); string xmlString = writer.ToString(); Console.WriteLine(xmlString); } } }
这将输出以下XML字符串:
<?xml version="1.0" encoding="utf-16"?><Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Name>John</Name> <Age>30</Age> </Person>
- 若要反序列化XML字符串回
Person
对象,可以使用Deserialize
方法:
using System; using System.IO; using System.Xml.Serialization; class Program { static void Main(string[] args) { string xmlString = @"<?xml version=""1.0"" encoding=""utf-16""?><Person xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <Name>John</Name> <Age>30</Age> </Person>"; XmlSerializer serializer = new XmlSerializer(typeof(Person)); using (StringReader reader = new StringReader(xmlString)) { Person person = (Person)serializer.Deserialize(reader); Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); } } }
这将输出:
Name: John, Age: 30
这就是在C#中实现不同类型对象的XML序列化和反序列化的基本方法。你可以根据需要修改这些示例以处理更复杂的类和数据结构。