c#

C#中不同类型对象的XML序列化

小樊
82
2024-09-14 21:20:30
栏目: 编程语言

在C#中,可以使用System.Xml.Serialization命名空间中的XmlSerializer类来实现对不同类型对象的XML序列化

  1. 首先,创建一个简单的类,例如Person
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
  1. 接下来,创建一个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>
  1. 若要反序列化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序列化和反序列化的基本方法。你可以根据需要修改这些示例以处理更复杂的类和数据结构。

0
看了该问题的人还看了