在C#中,您可以通过使用特性(Attributes)和实现IXmlSerializable
接口来自定义XML序列化
方法1:使用特性(Attributes)
示例:
using System;
using System.IO;
using System.Xml.Serialization;
[XmlRoot("Person")]
public class Person
{
[XmlElement("Name")]
public string FullName { get; set; }
[XmlAttribute("Age")]
public int Age { get; set; }
[XmlIgnore]
public bool IsMale { get; set; }
}
class Program
{
static void Main(string[] args)
{
var person = new Person { FullName = "John Doe", Age = 30, IsMale = true };
var serializer = new XmlSerializer(typeof(Person));
using (var writer = new StreamWriter("person.xml"))
{
serializer.Serialize(writer, person);
}
}
}
方法2:实现IXmlSerializable
接口
实现IXmlSerializable
接口后,您需要提供自定义的读取和写入XML的方法。这样,您可以完全控制序列化和反序列化过程。
示例:
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
public class Person : IXmlSerializable
{
public string FullName { get; set; }
public int Age { get; set; }
public bool IsMale { get; set; }
public void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("Person");
writer.WriteElementString("Name", FullName);
writer.WriteAttributeString("Age", Age.ToString());
if (IsMale)
{
writer.WriteElementString("Gender", "Male");
}
else
{
writer.WriteElementString("Gender", "Female");
}
writer.WriteEndElement();
}
public void ReadXml(XmlReader reader)
{
reader.ReadStartElement("Person");
FullName = reader.ReadElementString("Name");
Age = int.Parse(reader.GetAttribute("Age"));
var gender = reader.ReadElementString("Gender");
IsMale = gender == "Male";
reader.ReadEndElement();
}
public XmlSchema GetSchema()
{
return null;
}
}
class Program
{
static void Main(string[] args)
{
var person = new Person { FullName = "John Doe", Age = 30, IsMale = true };
var serializer = new XmlSerializer(typeof(Person));
using (var writer = new StreamWriter("person.xml"))
{
serializer.Serialize(writer, person);
}
}
}
这两种方法都可以实现自定义的XML序列化。使用特性(Attributes)的方法更简单,但如果您需要更多的控制权,请实现IXmlSerializable
接口。