XmlUtil.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using System.Xml.Serialization;
  6. namespace Ips.Library.Basic
  7. {
  8. public static class XmlUtil
  9. {
  10. public static void ToXmlFile(string fileName, object obj)
  11. {
  12. StreamWriter writer = null;
  13. try
  14. {
  15. XmlSerializer serializer = new XmlSerializer(obj.GetType());
  16. writer = new StreamWriter(fileName, false, Encoding.UTF8);
  17. serializer.Serialize(writer, obj);
  18. writer.Close();
  19. }
  20. catch
  21. {
  22. if (writer != null)
  23. writer.Close();
  24. throw;
  25. }
  26. }
  27. public static string ToXmlString(object obj)
  28. {
  29. var xmlSerializer = new XmlSerializer(obj.GetType());
  30. using (var stringWriter = new StringWriter())
  31. {
  32. xmlSerializer.Serialize(stringWriter, obj);
  33. using (var streamReader = new StringReader(stringWriter.GetStringBuilder().ToString()))
  34. {
  35. return streamReader.ReadToEnd();
  36. }
  37. }
  38. }
  39. public static object FromXmlFile(string fileName, Type type)
  40. {
  41. StreamReader reader = null;
  42. try
  43. {
  44. XmlSerializer serializer = new XmlSerializer(type);
  45. reader = new StreamReader(fileName);
  46. object obj = serializer.Deserialize(reader);
  47. reader.Close();
  48. return obj;
  49. }
  50. catch (Exception)
  51. {
  52. if (reader != null)
  53. reader.Close();
  54. return null;
  55. }
  56. }
  57. public static object FromXmlString(string xmlString, Type type)
  58. {
  59. var x = new XmlSerializer(type);
  60. var r = new StringReader(xmlString);
  61. return x.Deserialize(r);
  62. }
  63. public static T FromXmlString<T>(string xmlString)
  64. {
  65. var x = new XmlSerializer(typeof(T));
  66. var r = new StringReader(xmlString);
  67. return (T)x.Deserialize(r);
  68. }
  69. }
  70. }