新建控制台console项目,添加XmlPersonIXmlSerializable类,和AddressIXmlSerializable类(实现IXmlSerializable)以及AddressIXmlSerializable子类USAddressIXmlSerializable
代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace SupremeConsole { #region 测试IXmlSerializable public class XmlPersonIXmlSerializable { /// <summary> /// 姓名 /// </summary> public string Name { get; set; } /// <summary> /// 住址 /// </summary> public AddressIXmlSerializable HomeAddress = new USAddressIXmlSerializable();//子类的序列化 } public class AddressIXmlSerializable : IXmlSerializable { public string Street, PostCode; public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { reader.ReadStartElement(); Street = reader.ReadElementContentAsString("Street", null); PostCode = reader.ReadElementContentAsString("PostCode", null); reader.ReadEndElement(); } public void WriteXml(XmlWriter writer) { writer.WriteElementString("Street", Street); writer.WriteElementString("PostCode", PostCode); } } public class USAddressIXmlSerializable : AddressIXmlSerializable { public string Neighbor; } #endregion }
主方法代码:
using log4net; using System; using System.Data; using System.Data.SQLite; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.IO.MemoryMappedFiles; using System.IO.Pipes; using System.Linq; using System.Net; using System.Security.AccessControl; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using System.Reflection; using System.ServiceModel; using System.ServiceModel.Channels; using System.Runtime.Serialization; using System.Collections.Generic; namespace SupremeConsole { class Program { static void Main(string[] args) { XmlPersonIXmlSerializable xmlPersonIXmlSerializable = new XmlPersonIXmlSerializable { Name = "11111", HomeAddress = new AddressIXmlSerializable { Street = "大街三三号", PostCode = "123" } }; string s = SerializeManager.Instance.XmlSerialize<XmlPersonIXmlSerializable>(xmlPersonIXmlSerializable);//序列化 Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("测试序列化成功。。。"); Console.WriteLine($"测试序列化结果: {s}"); Console.ReadLine(); } } }
运行结果: