Model与XML互相转换

前端之家收集整理的这篇文章主要介绍了Model与XML互相转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. interface ISerialize
  2. {
  3. /// <summary>
  4. /// xml 转换为 model
  5. /// </summary>
  6. /// <typeparam name="T"></typeparam>
  7. /// <param name="xml"></param>
  8. /// <param name="model"></param>
  9. /// <returns></returns>
  10. T XmlToModel<T>(string xml,T model);
  11.  
  12.  
  13. /// <summary>
  14. /// model 转换为xml
  15. /// </summary>
  16. /// <typeparam name="T"></typeparam>
  17. /// <param name="model"></param>
  18. /// <returns></returns>
  19. string ModelToXml<T>(T model);
  20.  
  21.  
  22. /// <summary>
  23. /// xml 转换为Table
  24. /// </summary>
  25. /// <param name="xml"></param>
  26. /// <returns></returns>
  27. DataTable XmlToTable(string xml);
  28.  
  29.  
  30. /// <summary>
  31. /// 获取对应XML节点的值
  32. /// </summary>
  33. /// <param name="?"></param>
  34. /// <returns></returns>
  35. string XmlAnalysis(string stringRoot,string xml);
  36. }




  1. public class Serialize:ISerialize
  2. {
  3.  
  4. public T XmlToModel<T>(string xml,T model)
  5. {
  6. StringReader xmlReader = new StringReader(xml);
  7. XmlSerializer xmlSer = new XmlSerializer(typeof(T));
  8. return (T)xmlSer.Deserialize(xmlReader);
  9. }
  10.  
  11. public string ModelToXml<T>(T model)
  12. {
  13. MemoryStream stream = new MemoryStream();
  14. XmlSerializer xmlSer = new XmlSerializer(typeof(T));
  15. xmlSer.Serialize(stream,model);
  16.  
  17. stream.Position = 0;
  18. StreamReader sr = new StreamReader(stream);
  19. return sr.ReadToEnd();
  20. }
  21.  
  22.  
  23. public System.Data.DataTable XmlToTable(string xml)
  24. {
  25. StringReader xmlReader = new StringReader(xml);
  26. DataSet ds = new DataSet();
  27. ds.ReadXml(xmlReader);
  28. return ds.Tables[0];
  29. }
  30.  
  31.  
  32. public string XmlAnalysis(string stringRoot,string xml)
  33. {
  34. XmlDocument doc = new XmlDocument();
  35. doc.LoadXml(xml);
  36. return doc.DocumentElement.SelectSingleNode(stringRoot).InnerXml.Trim();
  37. }
  38. }
  1.  
  1. ISerialize s = new Serialize();
  2. //把XML文件转换为对应的实体类
  3.  
  4.  
  5. string xml = @"<Depart>
  6. <DepartID>123</DepartID>
  7. <PerSons>
  8. <PerSon>
  9. <name>张三</name>
  10. <age>3</age>
  11. </PerSon>
  12. <PerSon>
  13. <name>李斯</name>
  14. <age>56</age>
  15. </PerSon>
  16. </PerSons>
  17. </Depart>";
  18.  
  19.  
  20.  
  21.  
  22. //var info = s.XmlToModel<Depart>(xml,new Depart());
  23.  
  24.  
  25. // string newXml = s.ModelToXml<Depart>(info);
  26. // var Info = (Depart)XmlUtil.Deserialize(typeof(Depart),xml);
  27. s.XmlToTable(xml);

猜你在找的XML相关文章