string strXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Root><Users><User UserId=\"1\" UserName=\"王二\"/><User UserId=\"2\" UserName=\"张三\"/></Users></Root>"; var model = this.GetXmlObject(strXml, typeof(Root)) as Root; //<?xml version="1.0" encoding="utf-8"?> /// <summary> /// xml标签反序列化为对象 /// </summary> /// <param name="xml">xml格式字符串</param> /// <param name="type">转换类型</param> /// <returns>返回xml标签反序列化object对象</returns> public object GetXmlObject(string xml, Type type) { try { using (StringReader rdr = new StringReader(xml)) { XmlSerializer serializer = new XmlSerializer(type); return serializer.Deserialize(rdr);
} } catch (Exception) { return null; } } [Serializable] [XmlRoot("Root")] public class Root { [XmlArray("Users")] [XmlArrayItem("User")] public List<User> Users { get; set; } //[XmlElement("User")] } [Serializable] public class User { [XmlAttribute("UserId")] public string UserId { get; set; } [XmlAttribute("UserName")] public string UserName { get; set; } }