不可避免的遇到对接需要使用XML文档的第三方系统,某些节点内容特殊,序列化时需特殊处理,解决方案是实现IXmlSerializable接口。
////// Person /// public class Person : IXmlSerializable { ////// PersonId /// public int PersonId { get; set; } ////// PersonName /// public string PersonName { get; set; } ////// Birthday /// public DateTime? Birthday { get; set; } ////// Age /// public int Age { get; set; } ////// Remarks /// public string Remarks { get; set; } public XmlSchema GetSchema() { return default(XmlSchema); } public void ReadXml(XmlReader reader) { reader.ReadStartElement("Person"); this.PersonId = reader.ReadElementContentAsInt("PersonId",""); this.PersonName = reader.ReadElementContentAsString("PersonName",""); this.Birthday = reader.ReadElementContentAsDateTime("Birthday", ""); this.Age = reader.ReadElementContentAsInt("Age", ""); this.Remarks = reader.ReadElementContentAsString("Remarks", ""); } public void WriteXml(XmlWriter writer) { writer.WriteStartElement(nameof(this.PersonId)); writer.WriteValue(this.PersonId); writer.WriteEndElement(); writer.WriteStartElement(nameof(this.PersonName)); writer.WriteCData(this.PersonName); writer.WriteEndElement(); writer.WriteStartElement(nameof(this.Birthday)); writer.WriteValue(this.Birthday); writer.WriteEndElement(); writer.WriteStartElement(nameof(this.Age)); writer.WriteValue(this.Age); writer.WriteEndElement(); writer.WriteStartElement(nameof(this.Remarks)); writer.WriteCData(this.Remarks); writer.WriteEndElement(); } }
序列化:
XmlSerializer serializer = new XmlSerializer(typeof(Person)); Person person = new Person(); person.PersonId = 1; person.PersonName = chinesenames[0]; person.Birthday = RandomUtils.RandomDateTime(DateTime.Now.AddYears(-40), DateTime.Now); person.Age = DateTime.Now.Year - person.Birthday.GetValueOrDefault().Year; person.Remarks = "https://blog.csdn.net/shuliuzh/article/details/49426711"; using(MemoryStream writer=new MemoryStream()) { serializer.Serialize(writer, person); string xml= Encoding.UTF8.GetString(writer.GetBuffer()); Console.WriteLine(xml); File.WriteAllText("person.xml", xml, Encoding.UTF8); }
结果:
1 1985-05-24T00:00:00 33