Advertisement
dragonbs

Untitled

Dec 2nd, 2023
673
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.33 KB | None | 0 0
  1. using System.Text;
  2. using System.Xml.Serialization;
  3. using System.Xml;
  4.  
  5. namespace Artillery.Utilities;
  6.  
  7. public class XmlHelper
  8. {
  9.     public T Deserialize<T>(string inputXml, string rootName)
  10.     {
  11.         XmlRootAttribute xmlRoot = new XmlRootAttribute(rootName);
  12.         XmlSerializer xmlSerializer =
  13.             new XmlSerializer(typeof(T), xmlRoot);
  14.  
  15.         using StringReader reader = new StringReader(inputXml);
  16.         T deserializedDtos =
  17.             (T)xmlSerializer.Deserialize(reader);
  18.  
  19.         return deserializedDtos;
  20.     }
  21.  
  22.     public string Serialize<T>(T obj, string rootName)
  23.     {
  24.         StringBuilder sb = new StringBuilder();
  25.  
  26.         XmlRootAttribute xmlRoot =
  27.             new XmlRootAttribute(rootName);
  28.         XmlSerializer xmlSerializer =
  29.             new XmlSerializer(typeof(T), xmlRoot);
  30.  
  31.         XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
  32.         namespaces.Add(string.Empty, string.Empty);
  33.  
  34.         XmlWriterSettings settings = new XmlWriterSettings
  35.         {
  36.             Indent = true
  37.         };
  38.  
  39.         using (StringWriter writer = new StringWriter(sb))
  40.         using (XmlWriter xmlWriter = XmlWriter.Create(writer, settings))
  41.         {
  42.             xmlSerializer.Serialize(xmlWriter, obj, namespaces);
  43.         }
  44.  
  45.         return sb.ToString().TrimEnd();
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement