xml转实体类的实现
1、定义方法
public static T DESerializerStringToEntity<T>(string strXML) where T : class { try { using (StringReader sr = new StringReader(strXML)) { XmlSerializer serializer = new XmlSerializer(typeof(T)); return serializer.Deserialize(sr) as T; } } catch (Exception ex) { return null; } }
2、xml内容如下:
<request> <Id>11</Id> <Name>科技集团</Name> <Employees> <Employee> <Id>22</Id> <Name>张三</Name> </Employee> <Employee> <Id>22</Id> <Name>张三</Name> </Employee> </Employees> </request>
3、实体类如下:
[Serializable] [XmlRoot("request")] public class Company { public int Id { get; set; } public string Name { get; set; } [XmlArray("Employees"), XmlArrayItem("Employee")] public List<Employee> Employees { get; set; } } [XmlRoot(ElementName = "Employee")] public class Employee { public int Id { get; set; } public string Name { get; set; } }
4、调用
static void Main(string[] args) { string strXml = "<request><Id>11</Id><Name>科技集团</Name><Employees><Employee><Id>22</Id><Name>张三</Name></Employee><Employee><Id>22</Id><Name>张三</Name></Employee></Employees></request>"; Company Com = DESerializerStringToEntity<Company>(strXml); }