1、首先类需要增加[Serializable]标识
2、类实现IXmlSerializable接口
下面是重写ReadXml和WriteXml方法
public void ReadXml(XmlReader reader) { reader.ReadStartElement(reader.LocalName); while (reader.Read()) { if (reader.Name == "TimeType" && reader.NodeType == XmlNodeType.EndElement) { return; } if (reader.NodeType != XmlNodeType.Element) continue; bool result; switch (reader.Name) { case "Year": result = reader.Read(); if (result) { m_year = int.Parse(reader.Value); } break; case "Mon": result = reader.Read(); if (result) { m_mon = int.Parse(reader.Value); } break; case "Day": result = reader.Read(); if (result) { m_day = int.Parse(reader.Value); } break; case "Hour": result = reader.Read(); if (result) { m_hour = int.Parse(reader.Value); } break; case "Min": result = reader.Read(); if (result) { m_min = int.Parse(reader.Value); } break; case "Second": result = reader.Read(); if (result) { m_sec = int.Parse(reader.Value); } break; case "Millisecond": result = reader.Read(); if (result) { m_milisec = int.Parse(reader.Value); } break; case "Nanosecond": result = reader.Read(); if (result) { m_nanosec = int.Parse(reader.Value); } break; } } } public void WriteXml(XmlWriter writer) { writer.WriteStartElement("TimeType"); writer.WriteElementString("Year", Year.ToString()); writer.WriteElementString("Mon", Month.ToString()); writer.WriteElementString("Day", Day.ToString()); writer.WriteElementString("Hour", Hour.ToString()); writer.WriteElementString("Min", Minute.ToString()); writer.WriteElementString("Second", Second.ToString()); writer.WriteElementString("Millisecond", Millisecond.ToString()); writer.WriteElementString("Nanosecond", Nanosecond.ToString()); writer.WriteEndElement(); }
标签:xml,WriteElementString,自定义,Read,writer,int,result,reader,序列化 From: https://www.cnblogs.com/log9527blog/p/18454256