using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace Shentun.Peis.PlugIns.Extensions { public class XmlHelper { public static string SerializeToXml(T obj) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (StringWriter textWriter = new StringWriter()) { serializer.Serialize(textWriter, obj); return textWriter.ToString(); } } public static T DeserializeXml(string xml) { var serializer = new XmlSerializer(typeof(T)); using var reader = new StringReader(xml); return (T)serializer.Deserialize(reader); } public static T DeserializeXmlAddRoot(string xml) { // 创建 XmlDocument 来修复 XML var xmlDoc = new XmlDocument(); // 添加根元素 var root = xmlDoc.CreateElement("root"); // 加载原始内容到根元素中 root.InnerXml = xml; xmlDoc.AppendChild(root); // 转换为字符串 string fixedXml = xmlDoc.OuterXml; var serializer = new XmlSerializer(typeof(T)); using var reader = new StringReader(fixedXml); return (T)serializer.Deserialize(reader); } public static string SerializeToXmlEmpty(T obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); XmlSerializer serializer = new XmlSerializer(typeof(T)); XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(); namespaces.Add("", ""); // 使用不带 BOM 的 UTF-8 编码 var utf8NoBom = new UTF8Encoding(false); // false 表示不包含 BOM using (MemoryStream memoryStream = new MemoryStream()) { using (StreamWriter streamWriter = new StreamWriter(memoryStream, utf8NoBom)) { serializer.Serialize(streamWriter, obj, namespaces); } string xml = utf8NoBom.GetString(memoryStream.ToArray()); // 使用正则表达式替换所有自闭合标签 System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"<(\w+)\s*/>"); xml = regex.Replace(xml, @"<$1>"); return xml; } } } }