Advertisement
aboya

Serializer

Jul 14th, 2020
1,667
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.53 KB | None | 0 0
  1.     public class mySerializer
  2.     {
  3.         public static string ObjectToXML<T>(T obj)
  4.         {
  5.             using (StringWriter stringWriter = new StringWriter(new StringBuilder()))
  6.             {
  7.                 XmlSerializer xmlSerializer = GetSerializer<T>();
  8.  
  9.                 XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
  10.                 namespaces.Add(string.Empty, string.Empty);
  11.  
  12.                 XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
  13.                 xmlWriterSettings.OmitXmlDeclaration = true; // remove <?xml ... >
  14.                 xmlWriterSettings.Indent = true;
  15.                 xmlWriterSettings.IndentChars = " ";
  16.                 xmlWriterSettings.NewLineChars = "\r\n";
  17.                 xmlWriterSettings.NewLineHandling = NewLineHandling.Replace;
  18.  
  19.  
  20.                 XmlWriter xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings);
  21.                 xmlSerializer.Serialize(xmlWriter, obj, namespaces);
  22.  
  23.                 return stringWriter.ToString();
  24.             }
  25.  
  26.  
  27.         }
  28.         public class NamespaceIgnorantXmlTextReader : XmlTextReader
  29.         {
  30.             public NamespaceIgnorantXmlTextReader(System.IO.TextReader reader) : base(reader) { }
  31.  
  32.             public override string NamespaceURI
  33.             {
  34.                 get { return ""; }
  35.             }
  36.         }
  37.  
  38.         // helper class to omit XML decl at start of document when serializing
  39.         public class XTWFND : XmlTextWriter
  40.         {
  41.             public XTWFND(System.IO.TextWriter w) : base(w) { Formatting = System.Xml.Formatting.Indented; }
  42.             public override void WriteStartDocument() { }
  43.         }
  44.  
  45.         public static string RemoveNamespaces(string xml)
  46.         {
  47.             XElement Xml = XElement.Parse(xml);
  48.             foreach (XElement XE in Xml.DescendantsAndSelf())
  49.             {
  50.                 // Stripping the namespace by setting the name of the element to it's localname only
  51.                 XE.Name = XE.Name.LocalName;
  52.                 // replacing all attributes with attributes that are not namespaces and their names are set to only the localname
  53.                 XE.ReplaceAttributes((from xattrib in XE.Attributes().Where(xa => !xa.IsNamespaceDeclaration) select new XAttribute(xattrib.Name.LocalName, xattrib.Value)));
  54.             }
  55.             return Xml.ToString();
  56.         }
  57.  
  58.         public static T ObjectFromXML<T>(string xml)
  59.         {
  60.           //  xml = RemoveNamespaces(xml);
  61.             using (StringReader stringReader = new StringReader(xml))
  62.             {
  63.               //  using (NamespaceIgnorantXmlTextReader xreader = new NamespaceIgnorantXmlTextReader(stringReader))
  64.              //   {
  65.                    
  66.                     //xreader.Namespaces = false;
  67.                     XmlSerializer serializer = GetSerializer<T>();
  68.                     return (T)serializer.Deserialize(stringReader);
  69.              //   }
  70.             }
  71.         }
  72.         public static T ObjectFromXML<T>(StringBuilder xml)
  73.         {
  74.             using (StringBuilderReader stringReader = new StringBuilderReader(xml))
  75.             {
  76.                 XmlSerializer serializer = GetSerializer<T>();
  77.                 return (T)serializer.Deserialize(stringReader);
  78.             }
  79.         }
  80.         public static T ObjectFromXMLInFile<T>(string filePath)
  81.         {
  82.  
  83.             using (StreamReader sr = new StreamReader(filePath))
  84.             {
  85.                 XmlSerializer serializer = GetSerializer<T>();
  86.                 return (T)serializer.Deserialize(sr);
  87.  
  88.             }
  89.         }
  90.  
  91.         public static T ObjectFromJson<T>(string input)
  92.         {
  93.             return JsonConvert.DeserializeObject<T>(input);
  94.         }
  95.         public static string ObjectToJson(object obj)
  96.         {
  97.             return JsonConvert.SerializeObject(obj, new Newtonsoft.Json.Converters.IsoDateTimeConverter());
  98.         }
  99.  
  100.         public static T ObjectFromJson<T>(string input, JsonSerializerSettings settings)
  101.         {
  102.  
  103.             return JsonConvert.DeserializeObject<T>(input, settings);
  104.         }
  105.         public static string ObjectToJson(object obj, Newtonsoft.Json.Formatting formatting, JsonSerializerSettings settings)
  106.         {
  107.             return JsonConvert.SerializeObject(obj, formatting, settings);
  108.         }
  109.  
  110.         private static ConcurrentDictionary<System.Type, XmlSerializer> serializers = new ConcurrentDictionary<System.Type, XmlSerializer>();
  111.         public static XmlSerializer GetSerializer<T>()
  112.         {
  113.             var type = typeof(T);
  114.             XmlSerializer result;
  115.             if (serializers.TryGetValue(type, out result)) return result;
  116.            
  117.             var attributes = type.GetCustomAttributes(typeof(XmlTypeAttribute), false);
  118.             var attributeOverride = new XmlAttributeOverrides();
  119.             if (attributes.Length > 0)
  120.             {
  121.                 var ns = ((XmlTypeAttribute)attributes[0]).Namespace;
  122.                 attributeOverride.Add(type,
  123.                                       new XmlAttributes
  124.                                       {
  125.                                           Xmlns = false,
  126.                                           XmlRoot = new XmlRootAttribute
  127.                                           {
  128.                                               Namespace = ns,
  129.                                              // Namespace = string.Empty,
  130.                                               ElementName = type.Name.Replace("Type", "")
  131.                                           }
  132.                                       });
  133.             }
  134.  
  135.             result = new XmlSerializer(type);
  136.             serializers.TryAdd(type, result);
  137.             return result;
  138.         }
  139.  
  140.  
  141.         static public string BeautifyXml(string xml)
  142.         {
  143.             try
  144.             {
  145.                 var stringBuilder = new StringBuilder();
  146.                 var element = XElement.Parse(xml);
  147.  
  148.                 var settings = new XmlWriterSettings();
  149.                 settings.OmitXmlDeclaration = true;
  150.                 settings.Indent = true;
  151.                 settings.NewLineOnAttributes = true;
  152.                
  153.                 using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
  154.                 {
  155.                     element.Save(xmlWriter);
  156.                 }
  157.                 element = null;
  158.  
  159.                 return stringBuilder.ToString();
  160.             }
  161.             catch
  162.             {
  163.                 return xml;
  164.             }
  165.         }
  166.  
  167.  
  168.     }
  169.  
  170.         protected static bool XmlGetNode(string sXml, string sNodeName, out string XmlFound)
  171.         {
  172.             bool retval = false;
  173.             XmlFound = string.Empty;
  174.             string sTest = string.Empty;
  175.             sXml = Regex.Replace(sXml, "(\r)|(\n)|(\t)", string.Empty, RegexOptions.IgnoreCase);
  176.  
  177.             if (sNodeName.Length > 0 && sXml.Length > 0)
  178.             {
  179.                 sTest = Regex.Replace(sXml, string.Format(@"^.*\<{0}", sNodeName), string.Format(@"<{0}", sNodeName), RegexOptions.IgnoreCase);
  180.                 //sTest = Regex.Replace(sTest,@String.Format(@"{0}\>.*$",sNodeName), String.Format(@"{0}>",sNodeName), RegexOptions.IgnoreCase | RegexOptions.RightToLeft);
  181.                 sTest = Regex.Replace(sTest, string.Format(@"</{0}>.*$", sNodeName), string.Format(@"</{0}>", sNodeName), RegexOptions.IgnoreCase);
  182.                 sTest = Xattribute(sTest);
  183.  
  184.             }
  185.             if (sTest.Length > 0)
  186.             {
  187.                 retval = true;
  188.                 XmlFound = sTest;
  189.             }
  190.             return retval;
  191.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement