在C#中,您可以通過使用特性(Attributes)和實(shí)現(xiàn)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:實(shí)現(xiàn)IXmlSerializable
接口
實(shí)現(xiàn)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);
}
}
}
這兩種方法都可以實(shí)現(xiàn)自定義的XML序列化。使用特性(Attributes)的方法更簡單,但如果您需要更多的控制權(quán),請(qǐng)實(shí)現(xiàn)IXmlSerializable
接口。