using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Xml.Linq; using System.Xml.Serialization; namespace Asb.Base.V2; public static class SerializationExtensions { private static readonly Dictionary xmlSerializers = new Dictionary(); private static readonly object serializersLock = new object(); public static string ToXml(this object value) { string xmlText = string.Empty; if (value != null) { try { using TextWriter textWriter = new StringWriter(CultureInfo.CurrentCulture); lock (serializersLock) { XmlSerializer typeSerializer = GetTypeSerializer(value.GetType()); if (typeSerializer != null) { typeSerializer.Serialize(textWriter, value); xmlText = textWriter.ToString(); } } } catch { } } return NormalizeXmlText(xmlText); } private static XmlSerializer GetTypeSerializer(Type objectType) { XmlSerializer xmlSerializer = null; if (objectType != null) { lock (serializersLock) { if (!xmlSerializers.ContainsKey(objectType)) { string defaultNamespace = "urn:invensys.schemas"; object[] customAttributes = objectType.GetCustomAttributes(inherit: true); for (int i = 0; i < customAttributes.Length; i++) { if (customAttributes[i] is XmlRootAttribute xmlRootAttribute) { defaultNamespace = xmlRootAttribute.Namespace; break; } } xmlSerializer = new XmlSerializer(objectType, defaultNamespace); xmlSerializers.Add(objectType, xmlSerializer); } else { xmlSerializer = xmlSerializers[objectType]; } } } return xmlSerializer; } private static string NormalizeXmlText(string xmlText) { if (string.IsNullOrEmpty(xmlText)) { return xmlText; } if (Environment.Is64BitProcess) { using StringReader textReader = new StringReader(xmlText); using IEnumerator enumerator = XDocument.Load(textReader).Elements().GetEnumerator(); if (enumerator.MoveNext()) { XElement current = enumerator.Current; XAttribute xAttribute = current.Attribute(XNamespace.Xmlns + "xsd"); XAttribute xAttribute2 = current.Attribute(XNamespace.Xmlns + "xsi"); if (xAttribute != null && xAttribute2 != null) { current.ReplaceAttributes(xAttribute2, xAttribute); } using TextWriter textWriter = new StringWriter(CultureInfo.CurrentCulture); current.Save(textWriter); xmlText = textWriter.ToString(); } } return xmlText; } }