You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.4 KiB

2 years ago
1 week ago
2 years ago
1 year ago
2 years ago
1 week ago
2 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Xml;
  7. using System.Xml.Serialization;
  8. namespace Shentun.Peis.PlugIns.Extensions
  9. {
  10. public class XmlHelper
  11. {
  12. public static string SerializeToXml<T>(T obj)
  13. {
  14. XmlSerializer serializer = new XmlSerializer(typeof(T));
  15. using (StringWriter textWriter = new StringWriter())
  16. {
  17. serializer.Serialize(textWriter, obj);
  18. return textWriter.ToString();
  19. }
  20. }
  21. public static T DeserializeXml<T>(string xml)
  22. {
  23. var serializer = new XmlSerializer(typeof(T));
  24. using var reader = new StringReader(xml);
  25. return (T)serializer.Deserialize(reader);
  26. }
  27. public static T DeserializeXmlAddRoot<T>(string xml)
  28. {
  29. // 创建 XmlDocument 来修复 XML
  30. var xmlDoc = new XmlDocument();
  31. // 添加根元素
  32. var root = xmlDoc.CreateElement("root");
  33. // 加载原始内容到根元素中
  34. root.InnerXml = xml;
  35. xmlDoc.AppendChild(root);
  36. // 转换为字符串
  37. string fixedXml = xmlDoc.OuterXml;
  38. var serializer = new XmlSerializer(typeof(T));
  39. using var reader = new StringReader(fixedXml);
  40. return (T)serializer.Deserialize(reader);
  41. }
  42. }
  43. }