Xml 串行化类型

新建一个类 Topic 如下:

[Serializable] [XmlRoot("topic")] public class Topic { ///

/// 主题id /// [XmlElement("id")] public string Id { get; set; } /// /// 昵称 /// [XmlElement("nick")] public string Nick { get; set; } /// /// 标题 /// [XmlElement("title")] public string Title { get; set; } /// ///详细信息 /// [XmlElement("content")] public string Content { get; set; } /// /// 对象创建时间(格式:yyyy-MM-dd HH:mm:ss) /// [XmlElement("created")] public string Created { get; set; } /// /// 对象修改时间(格式:yyyy-MM-dd HH:mm:ss) [XmlElement("modified")] public string Modified { get; set; } }

xml文件如下:

2005-06-19 08:57:06 2010-07-02 18:02:15

序列化类 如下:

[Serializable] [XmlRoot("blog")] public class XmlParseList { public List List { get; set; } public static XmlParseList ParseXml(string element, string body) { XmlAttributes attrs = new XmlAttributes(); attrs.XmlElements.Add(new XmlElementAttribute(element, typeof(T))); XmlAttributeOverrides attrOvrs = new XmlAttributeOverrides(); attrOvrs.Add(typeof(XmlParseList), "List", attrs); XmlSerializer serializer = new XmlSerializer(typeof(XmlParseList), attrOvrs); object obj = serializer.Deserialize(new StringReader(body)); return obj as XmlParseList; } }

 

调用如下:

XDocument doc = XDocument.Load("../../XMLFile1.xml"); List list = XmlParseList.ParseXml("topic", doc.ToString()).List;

你可能感兴趣的:(Xml,.net)