举例C#使用特性排除某些类成员不参与XML序列化和反序列化

在C#中,可以使用 XmlIgnore 特性来排除某些类成员不参与XML序列化和反序列化。这个特性告诉XML序列化器忽略被标记的成员。

以下是一个使用 XmlIgnore 特性的示例:

csharp 复制代码
using System;
using System.IO;
using System.Xml.Serialization;

public class Person
{
    public string Name { get; set; }

    public int Age { get; set; }

    [XmlIgnore]
    public string Address { get; set; }
}

public class Program
{
    static void Main()
    {
        // 创建一个Person对象
        var person = new Person
        {
            Name = "John Doe",
            Age = 30,
            Address = "123 Main St"
        };

        // 将Person对象序列化为XML字符串
        string xmlString;
        using (var writer = new StringWriter())
        {
            var serializer = new XmlSerializer(typeof(Person));
            serializer.Serialize(writer, person);
            xmlString = writer.ToString();
        }

        Console.WriteLine(xmlString);

        // 将XML字符串反序列化为Person对象
        Person deserializedPerson;
        using (var reader = new StringReader(xmlString))
        {
            var serializer = new XmlSerializer(typeof(Person));
            deserializedPerson = (Person)serializer.Deserialize(reader);
        }

        Console.WriteLine($"Name: {deserializedPerson.Name}");
        Console.WriteLine($"Age: {deserializedPerson.Age}");
        Console.WriteLine($"Address: {deserializedPerson.Address}");
    }
}
csharp 复制代码
<Person>
  <Name>John Doe</Name>
  <Age>30</Age>
</Person>
Name: John Doe
Age: 30
Address:

可以看到,在序列化时,生成的XML中只包含了 Name 和 Age 成员,而 Address 成员被排除在外。在反序列化后,Address 成员的值为默认值(null 或空字符串)。

相关推荐
BK贝壳5 小时前
布尔数组也能做按位取反、移位和乘法:bool-hybrid-array 的位运算在本机跑了一遍
开发语言·数据结构·python·性能优化·numpy
码完就睡9 小时前
数据结构——图的基础概念
数据结构
张人玉14 小时前
C#如何使用FreeSql连接数据库
数据库·c#·freesql
Go-higher15 小时前
C语言--数据结构-栈、队列、堆
c语言·数据结构
步峰代理-盾山15 小时前
R语言爬虫实战:使用httr与XML解析网页数据并进行统计分析
xml·开发语言·爬虫·r语言·网络爬虫
吴可可1231 天前
C#打断多段线实现方法
c#
郝学胜-神的一滴1 天前
Effective STL 条款 14:用扩容函数避免重新分配
linux·开发语言·网络·数据结构·c++·单片机
Regulus-Moon1 天前
Quorum:用一个不等式换掉分布式锁
数据结构·论文阅读·分布式·算法·系统架构
Kari111 天前
医药和制造行业的外文文档批量翻译,排版怎么保住?
开发语言·c#·制造