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.

80 lines
2.6 KiB

2 years ago
6 months ago
2 years ago
2 years ago
2 years ago
6 months ago
2 weeks 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. public static string SerializeToXmlEmpty<T>(T obj)
  43. {
  44. if (obj == null)
  45. throw new ArgumentNullException(nameof(obj));
  46. XmlSerializer serializer = new XmlSerializer(typeof(T));
  47. XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
  48. namespaces.Add("", "");
  49. // 使用不带 BOM 的 UTF-8 编码
  50. var utf8NoBom = new UTF8Encoding(false); // false 表示不包含 BOM
  51. using (MemoryStream memoryStream = new MemoryStream())
  52. {
  53. using (StreamWriter streamWriter = new StreamWriter(memoryStream, utf8NoBom))
  54. {
  55. serializer.Serialize(streamWriter, obj, namespaces);
  56. }
  57. string xml = utf8NoBom.GetString(memoryStream.ToArray());
  58. // 使用正则表达式替换所有自闭合标签
  59. System.Text.RegularExpressions.Regex regex =
  60. new System.Text.RegularExpressions.Regex(@"<(\w+)\s*/>");
  61. xml = regex.Replace(xml, @"<$1></$1>");
  62. return xml;
  63. }
  64. }
  65. }
  66. }