- interface ISerialize
- {
- /// <summary>
- /// xml 转换为 model
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="xml"></param>
- /// <param name="model"></param>
- /// <returns></returns>
- T XmlToModel<T>(string xml,T model);
- /// <summary>
- /// model 转换为xml
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="model"></param>
- /// <returns></returns>
- string ModelToXml<T>(T model);
- /// <summary>
- /// xml 转换为Table
- /// </summary>
- /// <param name="xml"></param>
- /// <returns></returns>
- DataTable XmlToTable(string xml);
- /// <summary>
- /// 获取对应XML节点的值
- /// </summary>
- /// <param name="?"></param>
- /// <returns></returns>
- string XmlAnalysis(string stringRoot,string xml);
- }
- public class Serialize:ISerialize
- {
- public T XmlToModel<T>(string xml,T model)
- {
- StringReader xmlReader = new StringReader(xml);
- XmlSerializer xmlSer = new XmlSerializer(typeof(T));
- return (T)xmlSer.Deserialize(xmlReader);
- }
- public string ModelToXml<T>(T model)
- {
- MemoryStream stream = new MemoryStream();
- XmlSerializer xmlSer = new XmlSerializer(typeof(T));
- xmlSer.Serialize(stream,model);
- stream.Position = 0;
- StreamReader sr = new StreamReader(stream);
- return sr.ReadToEnd();
- }
- public System.Data.DataTable XmlToTable(string xml)
- {
- StringReader xmlReader = new StringReader(xml);
- DataSet ds = new DataSet();
- ds.ReadXml(xmlReader);
- return ds.Tables[0];
- }
- public string XmlAnalysis(string stringRoot,string xml)
- {
- XmlDocument doc = new XmlDocument();
- doc.LoadXml(xml);
- return doc.DocumentElement.SelectSingleNode(stringRoot).InnerXml.Trim();
- }
- }
- ISerialize s = new Serialize();
- //把XML文件转换为对应的实体类
- string xml = @"<Depart>
- <DepartID>123</DepartID>
- <PerSons>
- <PerSon>
- <name>张三</name>
- <age>3</age>
- </PerSon>
- <PerSon>
- <name>李斯</name>
- <age>56</age>
- </PerSon>
- </PerSons>
- </Depart>";
- //var info = s.XmlToModel<Depart>(xml,new Depart());
- // string newXml = s.ModelToXml<Depart>(info);
- // var Info = (Depart)XmlUtil.Deserialize(typeof(Depart),xml);
- s.XmlToTable(xml);