在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 或空字符串)。